Floats and casts in Rust
Floating point maths, and the explicit casts Rust demands between types.
fn main() {
let x = 2.0_f64;
println!("{:.4}", x.sqrt());
println!("{:.2}", (7.0 / 3.0));
let n = 9.87_f64;
let truncated = n as i32;
let widened = truncated as f64;
println!("{truncated} {widened}");
let close = (0.1 + 0.2_f64 - 0.3).abs() < f64::EPSILON;
println!("close: {close}");
}
How it works
ascasts truncate toward zero and never panic.- Comparing floats means comparing against an epsilon.
f64methods likesqrtandabslive on the value.
Keywords and builtins used here
asf64fni32letmain
The run, in numbers
- Lines
- 13
- Characters to type
- 288
- Tokens
- 92
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 69 seconds.
Step 5 of 6 in Variables & types, step 5 of 39 in Language basics.