如何在java中舍入整数
我想将数字1732舍入到最接近的十,十万。 我尝试使用Math round函数,但它只是为float和double编写的。 如何为整数做这个? java中有什么function吗?
使用精度 (Apache Commons Math 3.1.1)
Precision.round(double, scale); // return double Precision.round(float, scale); // return float
使用MathUtils (Apache Commons Math) – 旧版本
MathUtils.round(double, scale); // return double MathUtils.round(float, scale); // return float
scale – 小数点右边的位数。 (+/-)
因为使用圆形方法(浮点数,比例尺)而丢弃。
Math.round(MathUtils.round(1732,-1)); //最近十,1730
Math.round(MathUtils.round(1732,-2)); //最近的一百,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
你想用什么舍入机制? 对于正数,这是一种原始方法:
int roundedNumber = (number + 500) / 1000 * 1000;
这将带来1499到1000和1500到2000之类的东西。
如果你有负数:
int offset = (number >= 0) ? 500 : -500; int roundedNumber = (number + offset) / 1000 * 1000;
(int)(Math.round( 1732 / 10.0) * 10)
Math.round(double)
取double
Math.round(double)
,然后向上Math.round(double)
为最接近的整数。 因此, 1732
将在Math.round(1732 / 10.0)
处理时变为173.2
(输入参数Math.round(1732 / 10.0)
。 因此,该方法将其173.0
。 然后将它乘以10 (Math.round( 1732 / 10.0) * 10)
给出向下舍入的答案,然后173.0
将被转换为int
。
你可以尝试:
int y = 1732; int x = y - y % 10;
结果将是1730年。
编辑 :这不回答问题。 它只是删除了部分数字,但没有“舍入到最近的”。
最近十点:
int i = 1986; int result; result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
(随意加零,数十万)。
为什么不检查单位数字… 1.如果它小于或等于5,在单位位置加0并保留数字。 2.如果大于5,则增加十位数,在单位位置加0。
例如:1736(自6> = 5),舍入数字为1740.现在为1432(自2 <5)后,舍入数字将为1430 ....
我希望这会有效…如果不是让我知道这些案件……
快乐编程,
很简单。 尝试这个
int y = 173256457;int x = (y/10)*10;
现在在这里你可以用100,1000替换10等等….
很容易……
int x = 1234; int y = x – x%10; //它会给1230
int y = x – x%100; //它会给1200
int y = x – x%1000; //它会给1000
上面的逻辑只会将最后的数字转换为0.如果你想要实际轮数//例如。 1278这应该四舍五入到1280因为最后一个数字8> 5为此我写了一个函数检查出来。
private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit) { double tempSubtractNum = paramNumber%(10*noOfDigit); double tempResultNum = (paramNumber - tempSubtractNum); if(tempSubtractNum >= (5*noOfDigit)) { tempResultNum = tempResultNum + (10*noOfDigit); } return tempResultNum; }
这里传递2个参数,一个是数字,另一个是你需要四舍五入的位置。
此致,阿比纳夫
int val2 = 1732; val2 = (int)(Math.rint((double) i / 10) * 10);
输出是:1730
你看过Mathutils.round()的实现吗? 它全部基于BigDecimal和字符串转换。 很难想象许多效率较低的方法。
在不使用任何数学工具的情况下,可以对任何单位实现舍入,如下所示:
double roundValue (double input, double toNearest){ //toNearest is any rounding base like 10, 100 or 1000. double modValue = input % toNearest; System.out.println(modValue); if(modValue == 0d){ roundedValue = input; } else { roundedValue = ((input - modValue) + toNearest); } System.out.println(roundedValue); return roundedValue; }
我通常这样做:
int num = 1732; int roundedNum = Math.round((num + 9)/10 * 10);
这将给你1740的结果。
希望这会有所帮助。
我已经制作了这个简单的方法,它对我来说很好。 它会四舍五入到最接近的十,但很少调整你可以围绕100,1000等。
public int round10(int num){ if (num%10 < 5){ while (num%10!=0){ num--; } } else { while (num%10!=0){ num++; } } return num; }