Ben Chuanlong Du's Blog

It is never too late to learn.

Rounding Numbers in Kotlin

System.out.printf

In [1]:
System.out.printf("Pi: %.2f", 3.1415926)
Pi: 3.14
Out[1]:
java.io.PrintStream@510906c3

String.format

In [2]:
String.format("%1.2f", 3.1415926)
Out[2]:
3.14
In [3]:
"%1.2f".format(3.1415926)
Out[3]:
3.14

java.text.DecimalFormat

In [4]:
import java.text.DecimalFormat

DecimalFormat("#.##").format(3.1415926)
Out[4]:
3.14

kotlin.math.round

In [6]:
kotlin.math.round(3.1415926)
Out[6]:
3.0
In [7]:
kotlin.math.round(3.1415926 * 100) / 100.0
Out[7]:
3.14
In [9]:
%classpath add mvn org.apache.commons commons-math3 3.6.1
In [10]:
import org.apache.commons.math3.util.Precision

Precision.round(3.1415926, 2)
Out[10]:
3.14
In [ ]:

Comments