如何在Java中舍入一个两位小数位? [英] How do I round a double to two decimal places in Java?

查看:121
本文介绍了如何在Java中舍入一个两位小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我做了两到两位小数位数:

This is what I did to round a double to 2 decimal places:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

如果金额= 25.3569或类似的东西,这很好,但如果金额= 25.00或金额= 25.0,那么我得到25.0!我想要的是四舍五入,格式化为2位小数。

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.

推荐答案

你在做钱吗?创建一个字符串然后将其转换回来是非常循环的。

Are you doing money? Creating a string and then converting it back is pretty loopy.

使用BigDecimal。这已经被广泛讨论了。你应该有一个钱类,金额应该是一个BigDecimal。

Use BigDecimal. This has been discussed quite extensively. You should have a money class and the amount should be a BigDecimal.

即使你没有赚钱,也可以考虑BigDecimal。

Even if you're not doing money, consider BigDecimal.

这篇关于如何在Java中舍入一个两位小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆