查看原文:http://www.ibloger.net/article/157.html
4种方法,都是四舍五入,例,保留4位小数:
package com.arithmetic.demo;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Format {
static double f = 111231.55856666666;
public static void m1() {
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat转换最简便
*/
public static void m2() {
DecimalFormat df = new DecimalFormat("#.0000");
System.out.println(df.format(f));
}
/**
* String.format打印最简便
*/
public static void m3() {
System.out.println(String.format("%.4f", f));
}
public static void m4() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(4);
System.out.println(nf.format(f));
}
public static void main(String[] args) {
Format.m1();
Format.m2();
Format.m3();
Format.m4();
}
}
输出
111231.5586
111231.5586
111231.5586
111,231.5586