方法有好多种,在这里列出来4种:
1、用format方法,语法“String.format(“%.2f”,数值)”;
String的format方法(推荐)
double f = 111231.5585;
System.out.println(String.format("%.2f", f));
2、用DecimalFormat的format方法;
DecimalFormat的format方法
double f = 111231.5585;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
3、用setScale方法进行四舍五入;
BigDecimal的setScale方法
double f = 111231.5585;
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
4、用setMaximumFractionDigits方法。
NumberFormat的setMaximumFractionDigits方法
double f = 111231.5585;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(f));
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/75417.html