This article explores different ways to round up a float or a double with 2 decimal places in Kotlin.

1. Using roundToInt() function

The roundToInt() function rounds a double value to the nearest integer. It can be used as follows to round up a float or double with the required decimal places.

Download Code

 
The number of 0’s indicates the number of decimal places in the output. Therefore, to round with 4 decimal places, use value 10000.0:

Download Code

 
Also, consider this alternative and equivalent version of the above code:

Download Code

 
It’s worth noting that the floating-point arithmetic is very tricky, and might not always work as expected. For example, the value 295.335 gets rounded “down” to 295.33 instead of rounding “up” to 295.34.

Download Code

2. Using DecimalFormat.format() function

Alternatively, we can call the DecimalFormat.format() function to restrict the double to 2-decimal points using the pattern #.##. The RoundingMode can be provided using the setRoundingMode() function.

Download Code

 
Note that the number of # after the dot indicates the number of decimal places. Therefore, to round with 3 decimal places, use the pattern #.###:

Download Code

 
This solution faces the same issue as the roundToInt() function if no rounding mode is provided. i.e, the value 295.335 gets rounded “down” to 295.33 instead of rounding “up” to 295.34.

Download Code

3. Using String.format() function

We can also use the String.format() function to round up a float or a double with the specific number of decimal places. This works fine for the value 295.335, as shown below:

Download Code

4. Using BigDecimal

Finally, we can convert the double value to a BigDecimal and restrict the double to 2-decimal points using the setScale() function with the specified RoundingMode.

Download Code

That’s all about rounding up a float or a double with 2 decimal places in Kotlin.