Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Doubles, and Precision

Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23

like image 680
richsoni Avatar asked Jun 19 '12 18:06

richsoni


People also ask

What is a double in Scala?

In Scala, Double is a 64-bit floating point number, which is equivalent to Java's double primitive type. The -(x: Double) method is utilized to get the difference of given Double and Double value. Method Definition – def -(x: Char): Double. Returns – Returns the difference of this value and x.

How much precision does a double have?

In terms of number of precision it can be stated as double has 64 bit precision for floating point number (1 bit for the sign, 11 bits for the exponent, and 52* bits for the value), i.e. double has 15 decimal digits of precision.

How do you round off decimals in Scala?

You can do: Math. round(<double precision value> * 100.0) / 100.0 But Math. round is fastest but it breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)).


2 Answers

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble 

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).

like image 178
Travis Brown Avatar answered Sep 17 '22 13:09

Travis Brown


Here's another solution without BigDecimals

Truncate:

(math floor 1.23456789 * 100) / 100 

Round:

(math rint 1.23456789 * 100) / 100 

Or for any double n and precision p:

def truncateAt(n: Double, p: Int): Double = { val s = math pow (10, p); (math floor n * s) / s } 

Similar can be done for the rounding function, this time using currying:

def roundAt(p: Int)(n: Double): Double = { val s = math pow (10, p); (math round n * s) / s } 

which is more reusable, e.g. when rounding money amounts the following could be used:

def roundAt2(n: Double) = roundAt(2)(n) 
like image 37
Kaito Avatar answered Sep 20 '22 13:09

Kaito