typestar

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

  1. as casts truncate toward zero and never panic.
  2. Comparing floats means comparing against an epsilon.
  3. f64 methods like sqrt and abs live on the value.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 6 in Variables & types, step 5 of 39 in Language basics.

← Previous Next →