public class Test {
//保留两位小数第三位如果大于4会进一位(四舍五入)
double d = 6.23556;
/**
* 使用精确小数BigDecimal
*/
public void f1() {
BigDecimal bg = new BigDecimal(d);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat
*/
public void f2() {
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d));
}
/**
* String.format
*/
public void f3() {
System.out.println(String.format("%.2f", d));
}
/**
* 使用NumberFormat
*/
public void f4() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(d));
}
public static void main(String[] args) {
Test dt = new Test();
dt.f1();
dt.f2();
dt.f3();
dt.f4();
}
}
double截取小数点后两位
最新推荐文章于 2023-07-12 15:14:05 发布