防止在 Java 中的 String.format("%.2f", doubleValue) 中舍入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1305827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent round off in String.format("%.2f", doubleValue) in Java
提问by setzamora
How do I prevent String.format("%.2f", doubleValue);
from rounding off (round half up algorithm) instead of just truncating it?
如何防止String.format("%.2f", doubleValue);
四舍五入(四舍五入算法)而不是截断它?
e.g.
例如
doubleValue = 123.459
after formatting,
格式化后,
doubleValue = 123.46
I just want to discard the last digit,
我只想丢弃最后一位,
123.45
I know there are other ways to do this, I just want to know if this is possible using the String.format.
我知道还有其他方法可以做到这一点,我只想知道使用 String.format 是否可行。
采纳答案by DmitryK
You can always set the rounding mode:
您始终可以设置舍入模式:
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
and then use String.Format() HALF_EVEN is used by default, but you can change it to CEILING
然后使用 String.Format() 默认使用 HALF_EVEN,但您可以将其更改为 CEILING
another no so flexible approach will be (but this is not what you asked about):
另一种不太灵活的方法是(但这不是您要问的):
DecimalFormat df = new DecimalFormat("###.##");
df.format(123.459);
回答by Alex Rodrigues
doubleValue = 123.459
doubleValue = Math.ceil(doubleValue*100)/100;
回答by andersonbd1
Looks like the answer is a big fat NO. http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#dndec"then the value will be rounded using the round half up algorithm"
看起来答案是一个大胖子。 http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#dndec“然后该值将使用四舍五入算法四舍五入”
I find it odd they'd do that, since NumberFormatter allows you to set RoundingMode. But as you say, there's other ways to do it. The obviously easiest being subtract .005 from your value first.
我觉得他们这样做很奇怪,因为 NumberFormatter 允许您设置 RoundingMode。但正如你所说,还有其他方法可以做到。显然最简单的方法是先从您的值中减去 0.005。
回答by user1716794
use String.format("%.2f", doubleValue - .005)
使用 String.format("%.2f", doubleValue - .005)