I am trying to generate a Numeric Range of Double by val arrayOfDoubles = (0.0 to 1.0 by 0.1).toArray
, but the resultant is not what I expected it to be. the result is something like Array(0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999)
. Why is it like this. I could use this code to get what I expect it to be:
val roundedArray = for (x <- arrayOfDoubles) yield BigDecimal(x).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble
Which results in Array[Double] = Array(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
But this looks really cumbersome and expensive for BigDecimal converts the double to String and then parse it.
Is there a way I could get the NumericRange already rounded to one decimal place?
Thanks.