import java.text.DecimalFormat;
public class numberFarmat {
public static void main(String[] args) {
double sd = 23.2558896635;
//第一种方法 10000.0这个小数点后只表示保留小数,和位数没关系。
double d1 = (double) (Math.round(sd*10000)/10000.0000000000);
double d2 = (double) (Math.round(sd*10000)/10000.0);
System.out.println("4位小数测试:"+d1);
System.out.println("4位小数测试:"+d2);
//第二种方法
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df3 = new DecimalFormat("##.000");
System.out.println("3位小数:"+df3.format(sd));
System.out.println("2位小数:"+df2.format(sd));
}
}
运行结果如下:
4位小数测试:23.2559
4位小数测试:23.2559
3位小数:23.256
2位小数:23.26
Java小数格式化技巧
本文介绍了使用Java进行小数格式化的两种方法:通过Math.round结合特定倍数实现四舍五入并保留指定小数位数;利用DecimalFormat类设置格式模板精确控制输出的小数位数。演示了如何保留2位、3位及4位小数。
994

被折叠的 条评论
为什么被折叠?



