Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Compare floating point numbers

  • At first we compare two floating point numbers we created.
  • Then we see that the floating point imprecision leads to lack of equality.
fn main() {
    let x = 1.0;
    let y = 2.0;
    let z = 1.0;

    println!("{}", x < y);
    println!("{}", x == z);
    println!();

    let x = 0.1 + 0.2;
    let y = 0.3;
    println!("{}", x);
    println!("{}", y);
    println!("{}", x == y);
}
true
true

0.30000000000000004
0.3
false