問題描述
如何防止 String.format("%.2f", doubleValue);
舍入(四舍五入算法)而不是截斷它?
How do I prevent String.format("%.2f", doubleValue);
from rounding off (round half up algorithm) instead of just truncating it?
例如
doubleValue = 123.459
格式化后,
doubleValue = 123.46
我只想丟棄最后一位,
123.45
我知道還有其他方法可以做到這一點,我只想知道這是否可以使用 String.format.
I know there are other ways to do this, I just want to know if this is possible using the String.format.
推薦答案
你可以隨時設置舍入模式:
You can always set the rounding mode:
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
然后使用 String.Format()默認使用 HALF_EVEN,但您可以將其更改為 CEILING
and then use String.Format() HALF_EVEN is used by default, but you can change it to CEILING
另一種不太靈活的方法是(但這不是你問的):
another no so flexible approach will be (but this is not what you asked about):
DecimalFormat df = new DecimalFormat("###.##");
df.format(123.459);
這篇關于防止 Java 中 String.format("%.2f", doubleValue) 的舍入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!