四舍五入到最近

Round up to nearest

本文关键字:最近 四舍五入      更新时间:2023-09-26

如果数字是37,我希望它四舍五入到40,如果数字是1086,我希望它四舍五入到2000。如果数字是453992,我想四舍五入到500000。

我真的不知道如何更一般地描述它,抱歉,但基本上,最高位的数字应该总是四舍五入到最接近的数字,其余的都是零。我知道如何正常四舍五入,我只是不知道如何清晰地处理数字之间的变化。

谢谢,

编辑:我删除了第4到10回合,因为这一回合似乎不适合其他回合,而且它真的没有必要。

假设所有值都是正整数:

function roundUp(x){
    var y = Math.pow(10, x.toString().length-1);
    x = (x/y);
    x = Math.ceil(x);
    x = x*y;
    return x;
}

现场演示: http://jsfiddle.net/fP7Z6/

我将使用以下函数

function specialRoundUp(num) {
    var factor = Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
    return factor * Math.ceil(num/factor);
}

我的幻想版本,可以正确处理小数和负数,并正确舍入到最接近的十次方,如OP要求:

roundToNearestPow(value) {
    var digits = Math.ceil(Math.log10(Math.abs(value) + 1));
    var pow = Math.pow(10, digits - 1);
    return Math.round(value / pow) * pow;
}
// roundToNearestPow(-1499.12345) => 1000
// roundToNearestPow( 1500.12345) => 2000

获取原始号码的长度:

var num;
var count = num.toString().length;

获取第一个数字:

var first = num.toString().substring(0, 1);

先++,再加count-1个零

从评论

确保number不是10的乘积:

if((num % 10) != 0)
{
    //do all above in this closure
}

我读起来像nearest integer, which is production of an integer and some power of 10

可以通过

得到
var myCeil = function(num){
  var power = Math.log(num,10) * Math.LOG10E;
  var head = Math.floor(power);
  var rest = power - orig;
  return Math.ceil(Math.pow(10,next))*Math.pow(10,orig);
}
i = [37, 1086, 453992];
console.log( i.map(myCeil) );
// -> [ 40, 2000, 500000 ]

如果你想四舍五入到最接近的10次方,试试这个(javascript)

function Round2NearestPowerOf10(x) {
    x = Math.round(x);
    var strLen = x.toString().length;
    var y = x / Math.pow(10, strLen);
    var rst = Math.pow(10, strLen - 1 + Math.round(y));
    return rst < 10 ? 10 : rst;
}

结果将四舍五入到10,100,1000,等等