四舍五入到 49,没有小数 java

round up double to 49, no decimal java

我需要四舍五入一个双精度数,因为它以 49 和 99 结尾,fx 数字 2138 应该四舍五入到 2149,数字 2150 应该四舍五入到 99,这使得数字 1-48 转到49 和 50-98 转到 99 我发现的一切都是关于将小数点四舍五入到 .99, 它必须是双倍的,因为该值已经使用以下代码四舍五入到小数点后 0 位:

DecimalFormat decimalFormat = new DecimalFormat("#");
String fromattedDouble = decimalFormat.format(xxx);

您可以使用的一个技巧是将当前数字加倍,四舍五入到最接近的 100,然后除以 2:

int start = 2132;                 // 2132
start = start*2;                  // 4264
start = (start + 50) / 100 * 100; // (4264 + 50) / 100 * 100 = 4300
start = start / 2;                // 2150
start = start - 1;                // 2149

使用这个逻辑:

2100 -> 2099
2132 -> 2149
2150 -> 2149

这应该可以满足您的要求:

public static int round(int value) {
    return ((value + 50) / 50 * 50) - 1;
}

你可以使用这个方法:

public static int round(double value) {
    value = Math.round(value);
    return (int)(value-(value%50))+49;
}

测试用例

0       -> 49
25      -> 49
49      -> 49
50      -> 99
75      -> 99
99      -> 99
100     -> 149
2138    -> 2149
2150    -> 2199
48.5    -> 49
49.5    -> 99
50.5    -> 99

下面的方法达到了预期的效果:

static int round_to_49(int i) {
    return ((i+50)/50*50)-1;
}

示例:

50: 99
46: 49
145: 149
154: 199