Math.ceil在位置1处最接近五

and*_*lrc 5 javascript algorithm math numbers

好的....

我有很多不受控制的数字我想要回合:

51255 -> 55000
25 -> 25
9214 -> 9500
13135 -> 15000
25123 -> 30000
Run Code Online (Sandbox Code Playgroud)

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

但有一种简单的方法可能会使用某些数学函数吗?

use*_*716 7

这是我迟到的答案.不使用任何Math方法.

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

演示: 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]
Run Code Online (Sandbox Code Playgroud)

或者这可能有点清洁:

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

演示: 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;
}
Run Code Online (Sandbox Code Playgroud)

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

return (x + ((5-(x%5))%5)) * i;
Run Code Online (Sandbox Code Playgroud)

并把它分散一点:

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;
}
Run Code Online (Sandbox Code Playgroud)