javascript - Math.ceil 到位置 1 最接近的五

标签 javascript algorithm math numbers

好的....

我有很多不受控制的数字要四舍五入:

51255 -> 55000
25 -> 25
9214 -> 9500
13135 -> 15000
25123 -> 30000

我尝试将数字修改为字符串并计算长度....

但是有没有一种使用一些数学函数的简单方法呢?

最佳答案

这是我迟来的回答。不使用 Math 方法。

function toN5( x ) {
    var i = 5;
    while( x >= 100 ) {x/=10; i*=10;}
    return ((~~(x/5))+(x%5?1:0)) * i;
}

演示: http://jsbin.com/ujamoj/edit#javascript,live

   [51255, 24, 25, 26, 9214, 13135, 25123, 1, 9, 0].map( toN5 );

// [55000, 25, 25, 30, 9500, 15000, 30000, 5, 10, 0]

或者这可能更简洁一些:

function toN5( x ) {
    var i = 1;
    while( x >= 100 ) {x/=10; i*=10;}
    return (x + (5-((x%5)||5))) * i;
}

演示: http://jsbin.com/idowan/edit#javascript,live

分解:

function toN5( x ) {
   //       v---we're going to reduce x to the tens place, and for each place
   //       v       reduction, we'll multiply i * 10 to restore x later.
    var i = 1;

   // as long as x >= 100, divide x by 10, and multiply i by 10.
    while( x >= 100 ) {x/=10; i*=10;}

   // Now round up to the next 5 by adding to x the difference between 5 and
   //    the remainder of x/5 (or if the remainder was 0, we substitute 5
   //    for the remainder, so it is (x + (5 - 5)), which of course equals x).

   // So then since we are now in either the tens or ones place, and we've
   //    rounded to the next 5 (or stayed the same), we multiply by i to restore
   //    x to its original place.
    return (x + (5-((x%5)||5))) * i;
}

或者为了避免逻辑运算符而只使用算术运算符,我们可以这样做:

return (x + ((5-(x%5))%5)) * i;

稍微展开一下:

function toN5( x ) {
    var i = 1;
    while( x >= 100 ) {
        x/=10; 
        i*=10;
    }
    var remainder = x % 5;
    var distance_to_5 = (5 - remainder) % 5;
    return (x + distance_to_5) * i;
}

关于javascript - Math.ceil 到位置 1 最接近的五,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7404922/

相关文章:

javascript - ExtJS 4 中的拖放小部件

javascript - Twitter Bootstrap typeahead 获取 id 发布数据

javascript - 如何将子div高度设置为父高度?

algorithm - 深度优先搜索的空间复杂度

algorithm - NSGA 2 : PseudoCode

algorithm - 行数和列数相等的矩阵

Python 和 matplotlib 绘制超出域的点,曲线拟合较差

javascript - 如何通过输入字段使用 React JS 更新 Highcharts

python - 二维数组python中的邻居

c - 为什么 pow(-infinity, positive non-integer) +infinity?