That’s definitely correct, but still things like this
val a: BigDecimal = 0.02 - 0.03
would give
a: BigDecimal = -0.009999999999999998
because calculation is done in Double
s.
Maybe it’s okay since you write non-trivial constant expressions not so often. But I personally really love Haskell’s approach to literals, where
1 :: Num p => p
1.0 :: Fractional p => p
There number literals are treated somewhat like a function, i.e. its result type depends on the required type (like functions with path-dependent return type in Scala), including all operations. It means that when you write
y :: Float -- or Double or BigDecimal or whatever
y = 0.02 - 0.03
subtraction is performed in terms of Float
(or Double
, or BigDecimal
, or whatever), thus giving correct and precise results.
This approach may not work so nice in Scala because of different type inference paradigm (thus, sometimes it can require too many type ascriptions) but I believe it can be harmonized (especially when we have scala.math.Numeric
, scala.math.Fractional
and etc).