&引用;四舍五入;Java中的整数

&引用;四舍五入;Java中的整数,java,math,rounding,Java,Math,Rounding,我需要取一个long并将其值四舍五入到最近的10s位置。因此: If the # is: Then it should become: ============================================== 243 240 288485 288480 6 0 107 100 1009

我需要取一个
long
并将其值四舍五入到最近的10s位置。因此:

If the # is:            Then it should become:
==============================================
243                     240
288485                  288480
6                       0
107                     100
1009                    1000
1019                    1010
我知道,
RoundingMode
可能对我有所帮助,但我能找到的所有示例都使用小数,而不是整数。有什么想法吗?

使用模

例如:

 int i= 243;
 System.out.println(i-(i%10));
其他方式:(取自重复问题)


您可以通过乘法和除法运算来实现这一点。整数除法将根据需要进行取整:

long roundDownToTen(long input){
    long intermediate = input/10;
    return input*10;
}
例如,如果输入为1024,则除法使中间值为102(因为实际值为102.4,被截断以长格式存储),乘法得到1020

您也可以使用一种方法,即减去单位数字(模)的值,这是艾尚的答案中建议的。

除以10(243/10=24.3)将其放入整数,乘以10。(24*10 = 240) 对所有值执行此操作,您应该具有正确的值

long roundDownToTen(long input){
    long intermediate = input/10;
    return input*10;
}