将双精度格式格式化为 2 位小数不起作用
我想将这个 double:
3.499999999999999
舍入到:
3.50
我已经使用了这两种方法:
DecimalFormat df = new DecimalFormat("0.00");
double result = Double.valueOf(df.format(input));
System.out.println(answer);
但
public double round(double input)
{
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(input);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
return (bd.doubleValue());
}
它不断打印:
3.5
有人有解决方案吗?因为我真的认为这应该有效。感谢您的帮助。
I want to round this double:
3.499999999999999
to:
3.50
And I already used these two methods:
DecimalFormat df = new DecimalFormat("0.00");
double result = Double.valueOf(df.format(input));
System.out.println(answer);
and
public double round(double input)
{
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(input);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
return (bd.doubleValue());
}
But It keeps printing:
3.5
Does anyone have a solution for this? Because I really think that this should work. Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的第一个解决方案非常非常接近。只需这样做:
您的版本不起作用的原因是您采用了
input
双精度,将其格式化为具有 2dp 的String
,然后将其转换回一个双
。然后,System.out.println
像往常一样打印double
,没有特殊的小数位规则。Your first solution is really, really close. Just do this:
The reason your version doesn't work is that you're taking the
input
double, formatting it as aString
with 2dp, but then converting it back to adouble
.System.out.println
is then printing thedouble
as it always would, with no special decimal-place rules.您可以使用 printf 格式,这可能更简单。
印刷
You can use the printf formatting which may be simpler.
prints
您是否尝试将
0
替换为#
?DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(输入));
根据 此处
#
如果数字不存在,将解析为 0Did you try replacing the
0
's with#
's?DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(input));
According to here the
#
will be resolved to 0 if the digit is absent您可以使用 apache commons-math 的 Precision 类
You can use Precision class of apache commons-math