-1

如何转换号码的后三位?数字将大于 8000。

例如:

从 249439 到 249000?

4

4 回答 4

6

您可以使用模运算符 获得最后三位数字%,该运算符(对于正数)计算整数除法后的余数;例如,249439 % 1000439

因此,要向下舍入到最接近的千位,您只需减去这三个数字:

var rounded = original - original % 1000;

(例如,如果original249439,那么rounded将是249000)。

于 2013-08-21T20:45:09.343 回答
1

我建议如下:

function roundLastNDigits (num, digits) {
    // making sure the variables exist, and are numbers; if *not* we quit at this point:
    if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
        return false;
    }
    else {
        /* otherwise we:
           - divide the number by 10 raised to the number of digits
             (to shift divide the number so that those digits follow
             the decimal point), then
           - we round that number, then
           - multiply by ten raised to the number of digits (to
             recreate the same 'size' number/restoring the decimal fraction
             to an integer 'portion' */
        return Math.round(num / Math.pow(10, parseInt(digits,10))) * Math.pow(10,digits);
    }
}

console.log(roundLastNDigits(249439, 3))

JS 小提琴演示

如果您希望始终向下舍入我将修改上述内容以提供:

function roundLastNDigits (num, digits) {
    if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
        return false;
    }
    else {
        return Math.floor(num / Math.pow(10, parseInt(digits,10))) * Math.pow(10,digits);
    }
}

console.log(roundLastNDigits(8501, 3))

JS 小提琴演示

通过结合ruak 的天才方法来简化上述内容:

function roundLastNDigits (num, digits) {
    if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
        return false;
    }
    else {
        return num - (num % Math.pow(10,parseInt(digits,10)));
    }
}

console.log(roundLastNDigits(8501, 3))

JS 小提琴演示

或者,最后,假设您只需将最后三位字符替换为 0:

function roundLastNDigits (num, digits) {
    if (!num || !digits || !parseInt(digits,10)) {
        return false;
    }
    else {
        var reg = new RegExp('\\d{' + digits + '}$');
        return num.toString().replace(reg, function (a) {
            return new Array(parseInt(digits,10) + 1).join(0);
        });
    }
}

console.log(roundLastNDigits(8501, 3))

JS 小提琴演示

参考:

于 2013-08-21T20:39:33.633 回答
0

对于总是四舍五入,我建议将 out 分割1000,转换为Int然后乘回1000

var x = 249439,
    y = ((x / 1000) | 0) * 1000; // 249000
于 2013-08-21T20:39:18.630 回答
0

1) Math.round(num.toPrecision(3));

这不考虑要舍入的第三个值之前的值。

2)

这是一个糟糕的解决方案,但它有效。num = 50343 // 无论你的输入是什么。

m = 10^n。

数学.round(num*m)/m

n 是您想要移动的数量。

于 2013-08-21T20:43:07.383 回答