- 方法1
BigDecimal bd = new BigDeciaml(variable).setScale(4, BigDecimal.ROUND_HALF_UP);
double result1 = db.doubleValue();
- 方法2DecimalFormat不仅可以保留小数位,还可以用作转化小数为百分数
DecimalFormat df = new DecimalFormat("#.0000");
String result2 = df.format(variable);
- 方法3
String result3 = String.format("%.4f", variable);
- 方法4
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(4);
String result4 = nf.format(variable);

本文对比了四种常见的Java数值格式转换方法:BigDecimal的精确控制、DecimalFormat的百分比格式、String.format的简洁表达以及NumberFormat的定制精度。通过实例演示,帮助开发者理解和选择最合适的格式化方式。

3862

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



