Java保留两位小数的多种方法

新逸网络 1.9K 0

方法一

此方法返回精度为四舍五入

#.## 格式化后如果小数部分都是0,返回整数

#0.00 格式化后,保留2位小数

DecimalFormat df = new DecimalFormat("#0.00");
double d1 = 3.14159;
double d2 = 1.956;
double d3 = 2.0;
System.out.println(df.format(d1));
System.out.println(df.format(d2));
System.out.println(df.format(d3));
3.14
1.96
2.00

方法二

此方法 >5 时进1

double d = 123.4550;
BigDecimal decimal = new BigDecimal(d);
double value = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(value);
123.45

方法三

此方法返回精度为四舍五入

%.2f:%. 表示小数点前任意位数;2 表示两位小数;格式后的结果为f,表示浮点型

double d = 3.14159;
String result = String.format("%.2f", d);
System.out.println(result);
3.14

方法四

此方法返回精度为四舍五入

double d = 3.1445926;
NumberFormat format = NumberFormat.getNumberInstance();
// 参数digits是位数,最后位四舍五入
format.setMaximumFractionDigits(2);
String value = format.format(d);
System.out.print(value);
3.14

各种方法各有特点,如无特殊需要,建议使用BigDecimal,使用double处理精度的都被开除了!


本文链接:https://www.xinac.com/article/583.html

原文链接:https://blog.xinac.cn/archives/java-double-format.html


 

发表评论 取消回复
表情 图片 链接 代码

分享