Floating-Point Types in Rust

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we take a look at Floating-Point values and the f32 and f64 types. We'll also look at the different ways of defining and creating values of such types.

Instructor: [00:00] In Rust there are two different floating-point types. These are f32 and f64, which have a number range from very negative to very positive, including positive infinity and negative infinity.

[00:16] Floating point type values can be defined in many different ways, and here are some of them. For example, here we have -1.2345 or 3.nothing. There's also 034. What's important is that a floating point has different parts to it. There's the fractional part. There can also be an exponential part. This number right here says it's 1^4.

[00:45] Generally, what Rust will do is infer the type based on the value that is assigned. If both types would fit, so that is either f32 or f64, Rust will use f64 by default. It's also possible to apply a type suffix as part of the number, as we can see here. f5 is actually 32 of type f32. In this case, Rust will not infer the type because it's explicitly annotated.

[01:14] Here is another example of a floating-point type that includes all the parts that such a value can have. We have an integer part, then a fractional part, then exponential with a negative value, and a type annotation. All of these different parts of a fractional number are optional, but there has to be at least one of them to make the value a floating-point type.

[01:40] It's also important to note that Rust will never implicitly interpret an integer type as a floating-point type or vice versa. That's why in this particular case here, 32 would be an integer type. However, since there is the explicit annotation, Rust will interpret it as a floating-point type.