Floating point
- Rust course
- Beginner
- Lesson 14/115
- 4 min
Learn the f32 and f64 floating-point types.
Floating-point numbers
Rust has two floating-point types: f32 (single precision) and f64 (double precision, the default). On modern CPUs f64 is nearly as fast and more precise.
let pi = 3.14159; // f64
let yaricap: f32 = 2.0;
let alan = pi * 2.0 * 2.0;
println!("{:.2}", alan); // 12.57Integers and decimals can't be mixed directly: 2 * 1.5 compiles (literals) but n * 1.5 (n: i32) needs n as f64 * 1.5.
Comparing decimals
Because decimals are stored in binary, 0.1 + 0.2 == 0.3 is false. Comparison is done with a tolerance:
let a = 0.1 + 0.2;
println!("{}", a == 0.3); // false
println!("{}", (a - 0.3).abs() < 1e-10); // truef64::NAN isn't even equal to itself; that's why floats don't implement Eq and Ord, and total_cmp is used to sort them.
Practice Circle area
Declare let r: i32 = 3;. Compute the area with std::f64::consts::PI * (r as f64).powi(2) and print it with {:.2}.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let r: i32 = 3;
let alan = std::f64::consts::PI * (r as f64).powi(2);
println!("{:.2}", alan);
}Expected output
28.27
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>let n: i32 = 3; let x = n * 1.5;</code> compile?
- An i32 can't be multiplied by an f64; n as f64 is needed Correct answer
- 1.5 is invalid
- n is immutable
- It compiles
Explanation: Rust doesn't convert implicitly between number types; an explicit conversion is written with as.
2 Type conversion
let adet: i32 = 4;
let toplam = adet ____ f64 * 2.5;
let adet: i32 = 4;
let toplam = adet as f64 * 2.5;
Explanation: The as keyword converts explicitly between numeric types.
3 Expression and result
| Term | Meaning |
|---|---|
7.0 / 2.0 |
3.5 |
7 / 2 |
3 (integer) |
0.1 + 0.2 == 0.3 |
false |
2.0_f64.sqrt() |
1.414... |