The 4 methods are all rounded, for example:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class format {
double f = 111231.5585;
public void m1() {
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat conversion is the easiest
*/
public void m2() {
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(f));
}
/**
* String.format is the easiest to print
*/
public void m3() {
System.out.println(String.format("%.2f", f));
}
public void m4() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(f));
}
public static void main(String[] args) {
format f = new format();
f.m1();
f.m2();
f.m3();
f.m4();
}
}
There is also a direct upward integer
<h2 class="title content-title"> //java:Java rounding function</h2>
<div id="content" class="content mod-cs-content text-content clearfix"> //Math. floor(), Math.ceil(), BigDecimal are all rounding functions in Java, but the return value is different
Math.floor()
// The return value calculated by this function is the value after the decimal point is rounded off
// like:
Math.floor(3.2) //return 3
Math.floor(3.9) //return 3
Math.floor(3.0) //return 3
Math.ceil()
//The ceil function will return the integer part +1 as long as the decimal point is not 0
//like:
Math.ceil(3.2) //return 4
Math.ceil(3.9) //return 4
Math.ceil(3.0) //return 3 </div>