2016-02-08 72 views
0

我在Java中舍入问题(即整体= 1387.583515625输出是x = 5836而不是5835.我已经搜索过这个问题,我已经尝试了各种答案,但我仍然可以“不像是会得到它哟工作。任何想法?在Java中舍入错误

DecimalFormat df = new DecimalFormat(".####"); 
df.setRoundingMode(RoundingMode.CEILING); 

int x = Integer.parseInt(String.format(df.format(whole)).split("\\.")[1]); 
+2

如果您要求必须将它舍入,为什么输出是5835? – Ferrybig

+1

由RoundingMode.FLOOR替换RoundingMode.CEILING –

+0

oooooooh ....谢谢。我现在感到很蠢。 –

回答

1

这是非常清楚的this javadoc解释。

您需要使用RoundingMode.DOWN得到你想要什么,而不是RoundingMode.CEILING

enter image description here

+0

啊......谢谢。愚蠢的错误。 –

+0

不客气。如果没问题,请不要忘记用左边的复选标记标记您的问题。快乐的编码! – Derlin

+1

这是一个android问题,更好地引用android文档http://developer.android.com/reference/java/math/RoundingMode.html – weston

1

Be wary of the default locale!

默认的语言环境是不适合的机器可读的输出。

你的机器阅读本格式化输出,问题存在与该.split("\\.")它假定小数点分隔符是'.'。您在格式中指定'.'的事实既不在这里,也不在那里,将被文化中的分隔符替换。

替代

您可以通过指定Locale.US文化修复,但我可能会不使用字符串格式化和分裂只是为了得到一些从一些数字:

或者:

int x = (int)((whole - (int)whole) * 10000); 

或者:

int x = (int)(whole * 10000) % 10000; 

Math.abs如果whole可能是负数。