public class Test {
public static void main(String[] args) {
double d = 756.2345566;
//方法一:最简便的方法,调用DecimalFormat类
DecimalFormat df = new DecimalFormat(".00");
System.out.println(df.format(d));
//方法二:直接通过String类的format函数实现
System.out.println(String.format("%.2f", d));
//方法三:通过BigDecimal类实现
BigDecimal bg = new BigDecimal(d);
double d3 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(d3);
//方法四:通过NumberFormat类实现
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(d));
}
}
只保留两位小数,多余的删掉
最新推荐文章于 2024-03-15 19:11:38 发布
本文介绍了在Java编程语言中使用四种不同的方法来处理浮点数并将其格式化为保留两位小数的数值。这包括利用DecimalFormat类、String类的format函数、BigDecimal类以及NumberFormat类的具体实现方式。
1845

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



