格式化双精度到2位小数不起作用

编程入门 行业动态 更新时间:2024-10-24 13:26:50
本文介绍了格式化双精度到2位小数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

3.499999999999999

to:

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

有没有人有这个解决方案?因为我真的认为这应该是正常的。感谢您的帮助。

解决方案

您的第一个解决方案真的很真实。只要这样做:

DecimalFormat df = new DecimalFormat(0.00); System.out.println(df.format(input));

您的版本不起作用的原因是您正在使用输入 double,将其格式化为一个 String 与2dp,然后将其转换回 double 。 System.out.println 然后像往常一样打印 double ,没有特殊的小数位数规则。 / p>

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.

解决方案

Your first solution is really, really close. Just do this:

DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(input));

The reason your version doesn't work is that you're taking the input double, formatting it as a String with 2dp, but then converting it back to a double. System.out.println is then printing the double as it always would, with no special decimal-place rules.

更多推荐

格式化双精度到2位小数不起作用

本文发布于:2023-11-10 06:15:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数   精度   不起作用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!