java 总是四舍五入一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12625408/
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
Always rounding down a number
提问by MrD
I would like to know how I can instruct Java to always round down a given number.
我想知道如何指示 Java 始终舍入给定的数字。
E.g:
例如:
1.08 rounds to 1
1.88 rounds to 1
1.999999999999 rounds to 1
0.0002 rounds to 0
123.77 rounds to 123
Any suggestions?
有什么建议?
Thanks in advance! :)
提前致谢!:)
回答by assylias
That's what Math#floor
does:
那是什么Math#floor
呢:
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer
返回小于或等于参数且等于数学整数的最大(最接近正无穷大)双精度值
回答by Peter Lawrey
I would use Math.floor(double)
instead of Math.round(double)
我会用Math.floor(double)
而不是Math.round(double)
Or you can just cast if you want to round towards 0
或者,如果您想向 0 四舍五入,则可以直接施放
double d = 1.999999999999;
long l = (long) d;
回答by miss.serena
Math.floor function will do the trick.
Math.floor 函数可以解决问题。
Takes a double, Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
采用双精度值,返回小于或等于参数且等于数学整数的最大(最接近正无穷大)双精度值。
If you need it in a different form just cast it after (ie int)
如果您需要以不同的形式使用它,只需在(即 int)
The specs are here if you are curious how it works: http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html
如果您好奇它是如何工作的,这里有规范:http: //docs.oracle.com/javase/6/docs/api/java/lang/Math.html
if you need an example let me know and ill hook you up :)
如果你需要一个例子,让我知道,然后联系你 :)