Reputation: 11
How to justify below codes in Scala ? Can someone explain why does it return True in Example 3 and False in first two examples ?
Example 1:
scala> val f1 = 5.2
val f1: Double = 5.2
scala> val f2 = 5.2F
val f2: Float = 5.2
scala> f1==f2
val res8: Boolean = false
Example 2:
scala> val f1 = 5.24
val f1: Double = 5.24
scala> val f2 = 5.24F
val f2: Float = 5.24
scala> f1==f2
val res9: Boolean = false
Example 3:
scala> val f1 = 5.25
val f1: Double = 5.25
scala> val f2 = 5.25F
val f2: Float = 5.25
scala> f1==f2
val res10: Boolean = true
Upvotes: 1
Views: 84
Reputation: 27356
Nothing to do with Scala, but most decimal factions cannot be accurately represented as binary floating point numbers. For those numbers, the Float
value will be different from the Double
value so ==
will return false
.
In this case 5.25
does have an accurate binary floating point value (101.01
) so both the Float
and the Double
are the same.
Upvotes: 9