
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: October 1, 2024
In this tutorial, we’ll show how to round a number to the nearest and next multiple of 10 using the Scala standard library.
Scala standard library offers a Math.round() method, which rounds a given number to the closest Int:
scala> Math.round(4)
res0: Int = 4
scala> Math.round(4.1)
res1: Long = 4
scala> Math.round(4.9)
res2: Long = 5
Let’s see how we can use this to round to the next multiple of 10.
To round a number to the next multiple of 10, we can use the previous Math.round() method:
scala> Math.round(4.0/10) * 10
res3: Long = 0
scala> Math.round(6.0/10) * 10
res4: Long = 10
scala> Math.round(18.0/10) * 10
res5: Long = 20
scala> Math.round(21.0/10) * 10
res6: Long = 20
The idea here is to divide the given number by the multiple we want to round, then multiply the result with the multiple. Looking at the previous examples:
We should note that we need to have the original number as a double, otherwise, we get a wrong answer:
scala> 18/10
res0: Int = 1
scala> Math.round(18/10)
res1: Int = 1
scala> 18.0/10
res2: Double = 1.8
scala> Math.round(18.0/10)
res3: Long = 2
This is because the Int division is different from a Double division in Scala and Java. The Int division will just return the Int quotient and discard the remainder. On the opposite, the Double division returns the remainder, hence making our solution work properly when rounding the result of the division.
What if instead of the nearest we want the next multiple of 10? This can be solved by replacing the Math.round() method with Math.ceil() functions:
scala> Math.round(4.0/10) * 10
res17: Long = 0
scala> Math.ceil(4.0/10) * 10
res18: Double = 10.0
scala> Math.round(18.0/10) * 10
res19: Long = 20
scala> Math.ceil(18.0/10) * 10
res20: Double = 20.0
As we can see, by using the Math.ceil() function we can get the next multiple of 10.
To return the value as an Int instead of a Double, we can convert it easily using the Double.toInt() method:
scala> (Math.ceil(18.0/10) * 10).toInt
res23: Int = 20
For the sake of conciseness, we will omit this in the remaining examples.
We can also use the previous solutions to round a number to different numbers, simply by replacing 10 with the desired number in the code:
scala> Math.ceil(4.0/5) * 5
res23: Double = 5.0
scala> Math.ceil(12.0/5) * 5
res24: Double = 15.0
scala> Math.ceil(12.0/7) * 7
res25: Double = 14.0
scala> Math.ceil(13.0/2) * 2
res26: Double = 14.0
Here we rounded a few numbers to the next multiple of 5, 7, and 2, using the same approach as before.
In this article, we learned how to round a number to the next multiple of 10 using the Scala standard library. We also looked at rounding to the nearest multiple of 10, and even understood how to modify our solution to allow rounding to the multiple of any number.