Skip to content
Kavachकवच

Math: Exact numbers

● Beginner3 min

Numbers written in the code are worked out exactly, so 0.1 + 0.2 == 0.3 is true.

fn main() {
    print(0.1 + 0.2 == 0.3)
    let a = 0.1
    print(a + 0.2)
    print((a + 0.2).near(0.3))
}

The program ran and printed:

kavach run exact.kav

true0.30000000000000004true
exact.kav: Kavach code, then what running it prints

The compiler works out 0.1 + 0.2 exactly and rounds once. Values computed while the program runs are rounded at each step, as on every computer: compare those with near, or use Decimal.

More number traps of other languages, and what Kavach does instead: Classic Mistakes, Fixed.

What Kavach does for you

  • Constants are exact

    0.1 + 0.2 == 0.3 is true when both are constants: the compiler works constants out exactly, then rounds once.

    decision 0043