如何在java中舍入整数

Ach*_*ius 24 java

我想将数字1732舍入到最接近的十,十万.我尝试使用Math round函数,但它只针对float和double编写.如何为整数做这个?java中有什么功能吗?

Ebo*_*ike 25

你想用什么舍入机制?对于正数,这是一种原始方法:

int roundedNumber = (number + 500) / 1000 * 1000;
Run Code Online (Sandbox Code Playgroud)

这将带来1499到1000和1500到2000之类的东西.

如果你有负数:

int offset = (number >= 0) ? 500 : -500;
int roundedNumber = (number + offset) / 1000 * 1000;
Run Code Online (Sandbox Code Playgroud)


ila*_*lex 14

(int)(Math.round( 1732 / 10.0) * 10)
Run Code Online (Sandbox Code Playgroud)

Math.round(double)double并然后向上舍入为最接近的整数.因此,1732将成为173.2(输入参数)处理Math.round(1732 / 10.0).所以这个方法就像它一样173.0.然后将它乘以10 (Math.round( 1732 / 10.0) * 10)得到向下舍入的答案,173.0然后将其转换为int.


lsc*_*hin 13

使用精度(Apache Commons Math 3.1.1)

Precision.round(double, scale); // return double
Precision.round(float, scale); // return float
Run Code Online (Sandbox Code Playgroud)

使用MathUtils(Apache Commons Math) - 旧版本

MathUtils.round(double, scale); // return double
MathUtils.round(float, scale); // return float
Run Code Online (Sandbox Code Playgroud)

scale - 小数点右边的位数.(+/-)


因为方法轮(浮点数,比例)被使用而丢弃.

Math.round(MathUtils.round(1732,-1)); //最近十,1730
Math.round(MathUtils.round(1732,-2)); // nearest hundred,1700
Math.round(MathUtils.round(1732,-3)); //最接近千,2000


好的解决方案

int i = 1732;
MathUtils.round((double) i, -1); // nearest ten, 1730.0
MathUtils.round((double) i, -2); // nearest hundred, 1700.0
MathUtils.round((double) i, -3); // nearest thousand, 2000.0
Run Code Online (Sandbox Code Playgroud)


che*_*vim 6

你可以尝试:

int y = 1732;
int x = y - y % 10;
Run Code Online (Sandbox Code Playgroud)

结果将是1730年.

编辑:这不回答问题.它只是删除了部分数字,但没有"舍入到最近的".

  • 1736也将到1730年,这不会是最近的十. (4认同)
  • 在应用您的代码片段之前,将 5 添加到“y”,您就得到了常识中最接近的值。示例 1736 -> 1741 -> 1740。 (2认同)