如何在Java中舍入*向下*整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1783519/
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
How to round *down* integers in Java?
提问by Redandwhite
I'd like to round integers down to their nearest 1000 in Java.
我想在 Java 中将整数四舍五入到最接近的 1000。
So for example:
例如:
- 13,623 rounds to 13,000
- 18,999 rounds to 18,000
- etc
- 13,623 轮到 13,000
- 18,999 轮到 18,000 轮
- 等等
采纳答案by abyx
Simply divide by 1000 to lose the digits that are not interesting to you, and multiply by 1000:
简单地除以 1000 去掉你不感兴趣的数字,然后乘以 1000:
i = i/1000 * 1000
Or, you can also try:
或者,您也可以尝试:
i = i - (i % 1000)
回答by Poindexter
You could divide the number by 1000, apply Math.floor
, multiply by 1000 and cast back to integer.
您可以将数字除以 1000,应用Math.floor
,乘以 1000 并转换回整数。
回答by Alex
int i = Math.floorDiv(-13623, 1000) * 1000
//i => -14000
The above code will always round down (towards negative infinity) assuming the divisor (1000 in the example) is positive.
假设除数(示例中为 1000)为正数,上述代码将始终向下舍入(向负无穷大方向)。
The other answer (i = i/1000 * 1000
) rounds down when i
is positive, but up when i
is negative.
另一个答案 ( i = i/1000 * 1000
)i
为正时向下舍入,而i
为负时向上舍入。
-13623 / 1000 * 1000 == -13000
There is also a version of Math.floorDiv
for long
s which will work for very large numbers where the Math.floor
method might fail due to the precision of double
.
还有一个Math.floorDiv
for long
s版本,它适用于非常大的数字,其中该Math.floor
方法可能由于 的精度而失败double
。
There are also Math.floorMod
methods to go with the floorDiv
s which might allow you to shorten it a bit:
还有一些Math.floorMod
方法可以与floorDiv
s搭配使用,这可能会让您将其缩短一点:
int i = -13623;
i -= Math.floorMod(i, 1000);
//i => -14000