Whats up with adding two doubles? 3.4 + 4.3 == 7.6999999

I’ve finished a few coursera courses, now I feel brave enough to read through the docs.

On the value class doc page: Value Classes and Universal Traits | Scala Documentation

theres an example of creating a class for a Meter, which I dropped into a worksheet

Can anyone explain why 3.4 + 4.3 == 7.69999999 instead of 7.7?

// value class for representing a distance
class Meter(val value: Double) extends AnyVal {
  def +(m: Meter): Meter = new Meter(value + m.value)
}
val x = Meter(3.4) // Meter: 3.4
val y = Meter(4.3) // Meter: 4.3
val z = x + y // Meter: 7.699999999999999

println(z.value == 7.7) // false
println(z.value == 7.69) // false
println(z.value == 7.699999999999999) // true
println((3.4 + 4.3) == 7.7) // false
1 Like

ahh well it seems its just the same thing in all progamming languages with floating point arithmetic

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

3 Likes

1 Like