Ben Chuanlong Du's Blog

It is never too late to learn.

Round/Format Numbers in Java

System.out.printf

In [3]:
System.out.printf("Pi: %.2f", 3.1415926)
Pi: 3.14
Out[3]:
null

String.format

In [15]:
String fval = String.format("%1.2f", 3.1415926);
System.out.print(fval);
3.14
Out[15]:
null

java.text.DecimalFormat

In [9]:
import java.text.DecimalFormat;

DecimalFormat dfmat = new DecimalFormat("#.##");
double fval = Double.valueOf(dfmat.format(3.1415926));
System.out.print(fval);
3.14
Out[9]:
null

Math.round

In [12]:
import java.lang.Math;

double fval = Math.round(3.1415926);
System.out.print(fval);
3.0
Out[12]:
null
In [14]:
import java.lang.Math;

double fval = Math.round(3.1415926 * 100) / 100.0;
System.out.print(fval);
3.14
Out[14]:
null
In [ ]:
import org.apache.commons.math3.util.Precision;

double fval = Precision.round(3.1415926, 2);
System.out.print(fval);

Comments