145

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

3
  • 12
    After looking at all the answers I guess that the short answer is no? :) Commented Apr 20, 2017 at 14:09
  • 5
    @Gevorg You made me laugh. I am new to Scala from other numerics-heavy languages, and my jaw almost hit the floor reading this thread. This is an insane state of affairs for a programming language.
    – ely
    Commented Aug 9, 2018 at 21:22
  • 1
    Shouldn't be 1.24 if we start from the end? Commented Jan 6, 2023 at 15:30

15 Answers 15

189

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).

30
  • 5
    Fairly likely, I'd say. Anything involving grids or finance can require rounding and also performance.
    – Rex Kerr
    Commented Jun 19, 2012 at 20:33
  • 31
    I suppose there are people for whom a long call to a clunky library is more comprehensible than simple mathematics. I'd recommend "%.2f".format(x).toDouble in that case. Only 2x slower, and you only have to use a library that you already know.
    – Rex Kerr
    Commented Jun 19, 2012 at 20:52
  • 7
    @RexKerr, you are not rounding in this case.. simply truncating.
    – José Leal
    Commented Sep 27, 2012 at 6:59
  • 19
    @JoséLeal - Huh? scala> "%.2f".format(0.714999999999).toDouble res13: Double = 0.71 but scala> "%.2f".format(0.715).toDouble res14: Double = 0.72.
    – Rex Kerr
    Commented Apr 20, 2013 at 18:37
  • 5
    @RexKerr I prefer your string.format way, but in locales s.a. mine (Finnish), care must be taken to fix to ROOT locale. E.g. "%.2f".formatLocal(java.util.Locale.ROOT,x).toDouble . It seems, format uses ',' because of the locale whereas toDouble is not able to take it in and throws a NumberFormatException. This of course is based on where your code is being run, not where it's developed.
    – akauppi
    Commented Sep 19, 2014 at 10:02
86

Here's another solution without BigDecimals

Truncate:

(math floor 1.23456789 * 100) / 100

Round (see rint):

(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)
3
  • 8
    roundAt2 should be def roundAt2(n: Double) = roundAt(2)(n) no ?
    – C4stor
    Commented Sep 8, 2014 at 13:38
  • this seems to return incorrect result for NaN, isn't it?
    – jangorecki
    Commented Jul 18, 2016 at 23:42
  • the problem with floor is that truncateAt(1.23456789, 8) will return 1.23456788 while roundAt(1.23456789, 8) will return the correct value of 1.23456789 Commented Apr 23, 2017 at 21:25
40

Since no-one mentioned the % operator yet, here comes. It only does truncation, and you cannot rely on the return value not to have floating point inaccuracies, but sometimes it's handy:

scala> 1.23456789 - (1.23456789 % 0.01)
res4: Double = 1.23
3
  • 2
    Wouldn't recommend this though it's my own answer: the same inaccuracy issues as mentioned by @ryryguy in another answer's comment affect here as well. Use string.format with the Java ROOT locale (I'll comment about that there).
    – akauppi
    Commented Sep 19, 2014 at 9:59
  • this is perfect if you just need to render the value and never use it in subsequent operations. thanks Commented Dec 3, 2014 at 21:20
  • 4
    here is something funny: 26.257391515826225 - 0.057391515826223094 = 26.200000000000003
    – kubudi
    Commented Jul 9, 2015 at 14:37
16

How about :

 val value = 1.4142135623730951

//3 decimal places
println((value * 1000).round / 1000.toDouble)

//4 decimal places
println((value * 10000).round / 10000.toDouble)
2
  • pretty clean solution. Here is mine for truncation: ((1.949 * 1000).toInt - ((1.949 * 1000).toInt % 10)) / 1000.toDouble didn't test it too much though. This code would do 2 decimal places.
    – robert
    Commented Mar 30, 2016 at 7:45
  • This solution works but if I need zeros in the the decimal places e.g. to keep 4 decimal places it won't. But the format works correctly in this: "%.4f".format(myDoubleNumber) Examples: "%.4f".format(1.99999) will return 2.0000 "%.4f".format(1.23499) will return 1.2350 Of course the result is String so good for rendering only.
    – NKM
    Commented May 12, 2022 at 11:54
9

It's actually very easy to handle using Scala f interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html

Suppose we want to round till 2 decimal places:

scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198

scala> println(f"$sum%1.2f")
1.57
1
  • 1
    What if the X decimal places were a variable instead of predetermined? I've tried things like f"$y$xf" but no bueno. Commented Sep 3, 2020 at 20:52
7

Edit: fixed the problem that @ryryguy pointed out. (Thanks!)

If you want it to be fast, Kaito has the right idea. math.pow is slow, though. For any standard use you're better off with a recursive function:

def trunc(x: Double, n: Int) = {
  def p10(n: Int, pow: Long = 10): Long = if (n==0) pow else p10(n-1,pow*10)
  if (n < 0) {
    val m = p10(-n).toDouble
    math.round(x/m) * m
  }
  else {
    val m = p10(n).toDouble
    math.round(x*m) / m
  }
}

This is about 10x faster if you're within the range of Long (i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.

2
  • 3
    Watch out, multiplying by the reciprocal doesn't work reliably, because it may not be reliably representable as a double: scala> def r5(x:Double) = math.round(x*100000)*0.000001; r5(0.23515) ==> res12: Double = 0.023514999999999998. Divide by the significance instead: math.round(x*100000)/100000.0
    – ryryguy
    Commented Apr 19, 2013 at 22:37
  • It may also be useful to replace the recursive p10 function with an array lookup: the array will increase memory consumption by about 200 bytes but likely save several iterations per call. Commented Dec 31, 2018 at 19:44
5

For those how are interested, here are some times for the suggested solutions...

Rounding
Java Formatter: Elapsed Time: 105
Scala Formatter: Elapsed Time: 167
BigDecimal Formatter: Elapsed Time: 27

Truncation
Scala custom Formatter: Elapsed Time: 3 

Truncation is the fastest, followed by BigDecimal. Keep in mind these test were done running norma scala execution, not using any benchmarking tools.

object TestFormatters {

  val r = scala.util.Random

  def textFormatter(x: Double) = new java.text.DecimalFormat("0.##").format(x)

  def scalaFormatter(x: Double) = "$pi%1.2f".format(x)

  def bigDecimalFormatter(x: Double) = BigDecimal(x).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

  def scalaCustom(x: Double) = {
    val roundBy = 2
    val w = math.pow(10, roundBy)
    (x * w).toLong.toDouble / w
  }

  def timed(f: => Unit) = {
    val start = System.currentTimeMillis()
    f
    val end = System.currentTimeMillis()
    println("Elapsed Time: " + (end - start))
  }

  def main(args: Array[String]): Unit = {

    print("Java Formatter: ")
    val iters = 10000
    timed {
      (0 until iters) foreach { _ =>
        textFormatter(r.nextDouble())
      }
    }

    print("Scala Formatter: ")
    timed {
      (0 until iters) foreach { _ =>
        scalaFormatter(r.nextDouble())
      }
    }

    print("BigDecimal Formatter: ")
    timed {
      (0 until iters) foreach { _ =>
        bigDecimalFormatter(r.nextDouble())
      }
    }

    print("Scala custom Formatter (truncation): ")
    timed {
      (0 until iters) foreach { _ =>
        scalaCustom(r.nextDouble())
      }
    }
  }

}
6
  • 1
    Dear scalaCustom is not rounding off, it's just truncating Commented Jan 5, 2018 at 13:37
  • hmm, OP was not specific to rounding or truncating; ...truncate or round a Double.
    – cevaris
    Commented Jan 8, 2018 at 18:19
  • But in my opinion comparing the speed / execution time of truncating function of with rounding functions is inadequate. That's why I asked you to clarify it to the reader that the custom feature only truncate. And truncate / custom function mentioned by you can be simplified further. val doubleParts = double. toString.split(".") Now get the first two chars of doubleParts.tail and concat with strings "." and doubleParts. head and parse to double. Commented Jan 9, 2018 at 3:56
  • 1
    updated, look better? also your suggestion toString.split(".") and doubleParts.head/tail suggestion may suffer from extra array allocation plus string concatenation. would need to test to be sure though.
    – cevaris
    Commented Jan 10, 2018 at 21:27
  • @OldGaurd01 Your idea of "simplification" on a truncate/rounding function FOR NUMBERS, is to use a String??? In what universe is that a simplification?? At least 2 extra casts from Double -> String and String -> Double (potentially 2x for each part...). Commented Feb 27, 2021 at 13:39
4

You may use implicit classes:

import scala.math._

object ExtNumber extends App {
  implicit class ExtendedDouble(n: Double) {
    def rounded(x: Int) = {
      val w = pow(10, x)
      (n * w).toLong.toDouble / w
    }
  }

  // usage
  val a = 1.23456789
  println(a.rounded(2))
}
1
  • 1
    Please specify that this method is for truncating only and not properly rounding.
    – bobo32
    Commented May 25, 2017 at 16:10
3

Recently, I faced similar problem and I solved it using following approach

def round(value: Either[Double, Float], places: Int) = {
  if (places < 0) 0
  else {
    val factor = Math.pow(10, places)
    value match {
      case Left(d) => (Math.round(d * factor) / factor)
      case Right(f) => (Math.round(f * factor) / factor)
    }
  }
}

def round(value: Double): Double = round(Left(value), 0)
def round(value: Double, places: Int): Double = round(Left(value), places)
def round(value: Float): Double = round(Right(value), 0)
def round(value: Float, places: Int): Double = round(Right(value), places)

I used this SO issue. I have couple of overloaded functions for both Float\Double and implicit\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.

1
  • Also, you may use @rex-kerr 's approach for the power instead of Math.pow Commented May 18, 2013 at 4:22
3

Those are great answers in this thread. In order to better show the difference, here is just an example. The reason I put it here b/c during my work the numbers are required to be NOT half-up :

    import org.apache.spark.sql.types._
    val values = List(1.2345,2.9998,3.4567,4.0099,5.1231)
    val df = values.toDF
    df.show()
    +------+
    | value|
    +------+
    |1.2345|
    |2.9998|
    |3.4567|
    |4.0099|
    |5.1231|
    +------+

    val df2 = df.withColumn("floor_val", floor(col("value"))).
    withColumn("dec_val", col("value").cast(DecimalType(26,2))).
    withColumn("floor2", (floor(col("value") * 100.0)/100.0).cast(DecimalType(26,2)))

    df2.show()
+------+---------+-------+------+
| value|floor_val|dec_val|floor2|
+------+---------+-------+------+
|1.2345|        1|   1.23|  1.23|
|2.9998|        2|   3.00|  2.99|
|3.4567|        3|   3.46|  3.45|
|4.0099|        4|   4.01|  4.00|
|5.1231|        5|   5.12|  5.12|
+------+---------+-------+------+

floor function floors to the largest interger less than current value. DecimalType by default will enable HALF_UP mode, not just cut to precision you want. If you want to cut to a certain precision without using HALF_UP mode, you can use above solution instead ( or use scala.math.BigDecimal (where you have to explicitly define rounding modes).

2

Since the question specified rounding for doubles specifically, this seems way simpler than dealing with big integer or excessive string or numerical operations.

"%.2f".format(0.714999999999).toDouble
1

I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:

  /** Constructs a `BigDecimal` using the decimal text representation of `Double` value `d`, rounding if necessary. */
  def decimal(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)

I'm going to stick to math manipulations as Kaito suggested.

1

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)).

Use Bigdecimal it is bit inefficient as it converts the values to string but more reliable: BigDecimal(<value>).setScale(<places>, RoundingMode.HALF_UP).doubleValue() use your preference of Rounding mode.

If you are curious and want to know more detail why this happens you can read this: enter image description here

0

A bit strange but nice. I use String and not BigDecimal

def round(x: Double)(p: Int): Double = {
    var A = x.toString().split('.')
    (A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}
0

I think previous answers are:

  • Plain wrong: using math.floor for example doesn't work for negative values..
  • Unnecessary complicated.

Here is a suggestion based on @kaito's answer (i can't comment yet):

def truncateAt(x: Double, p: Int): Double = {
    val s = math.pow(10, p)
    (x * s).toInt / s
}

toInt will work for positive and negative values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.