简体   繁体   English

javascript舍入功能

[英]javascript rounding function

I want to write a function that given a number will set all but the first digit to zero and will increase the first digit by one 我想编写一个函数,给定一个数字将设置除第一个数字以外的所有数字为零,并将第一个数字增加一个

for example, 175 should become 200, 23 should become 30, etc. What is the best way to do this? 例如,175应该变为200,23应该变为30,等等。这样做的最佳方法是什么?

function truncUp(num) {
    var factor = Math.pow(10, (num+'').toString().length - 1);
    return Math.floor(num / factor) * factor + factor;
}

that was fun :D 这很有趣:D

And for the unnamed "others": 对于未命名的“其他人”:

function truncUp(num) {
    num = Math.floor(num);
    var factor = Math.pow(10, (Math.abs(num)+'').toString().length - 1);
    return Math.floor(num / factor) * factor + ((Math.abs(num) - num == 0?1:2)*factor);
}
function myRound(num)
{
    var digits = String(num).length - 1,
        pow = Math.pow(10, digits);
    num /= pow;
    num = Math.ceil(num);
    num *= pow;
    return num;
}

Short version: 精简版:

function myRound(num)
{
    var pow = Math.pow(10, String(num).length - 1);
    return Math.ceil(num/pow)*pow;
}

Tests: 测试:

> myRound(175)
  200
> myRound(23)
  30
> myRound(95)
  100

Divide the number until it is less then 10 (a.bcdefgh), remember how many times you divided, ceil, then multiply again. 将数字除以小于10(a.bcdefgh),记住你划分的次数,ceil,然后再次乘以。

function superRoundUp(n) {
    i = 0;
    while (n > 10) {
        i++;
        n = n/10; 
    }
    n = Math.ceil(n);
    for ( ; i>0; i--) {
        n = n * 10;
    }
    return n;
}
var n = 57;
alert(superRoundUp(n));

If you want to manipulate in decimal, sometimes the best way is to just treat it as a string of decimal digits. 如果你想用十进制来操作,有时候最好的方法就是将它当作一串十进制数字。

function oneSignificantDigitAwayFromZero(n) {
   // Convert to a string of digits.
   var s = "" + n;
   // This regexp grabs any sign, and leading zeros in one group,
   // the digit to promote in another, and the trailing digits in a third.
   // This regexp is guaranteed not to accidentally grab any exponent.
   return s.replace(/^(-?[0.]*)([1-9])([0-9.]+)/, function (_, before, digit, after) {
     // Round the digit up if there is a non-zero digit after it,
     // so 201 -> 300, but 200 -> 200.
     var roundUp = /[1-9]/.test(after) ? +digit + 1 : +digit;
     // Replace all non-zero digits after the one we promote with zero.
     // If s is "201", then after is "01" before this and "00" after.
     after = after.replace(/[1-9]/g, "0");
     // If roundUp has no carry, then the result is simple.
     if (roundUp < 10) { return before + roundUp + after; }
     // Otherwise, we might have to put a dot between the 1 and 0 or consume a zero from
     // the fraction part to avoid accidentally dividing by 10. 
     return before.replace(/0?([.])?$/, "1$10") + after;
   });
}

Ok, one more, using some String magic. 好的,还有一个,使用一些String魔法。 Similar to Josephs answer, but you avoid using any floating point operations (still not sure which one might be more efficient): 类似于约瑟夫的回答,但你避免使用任何浮点运算(仍不确定哪一个可能更有效):

function roundUp(number)
{
    var numberStr = number.toString();
    var firstDigit = parseInt(numberStr.substring(0, 1)) + 1;
    return firstDigit * Math.pow(10, (numberStr.length - 1));
};
alert(roundUp(23));

Most of the answears here uses strings. 这里的大多数answears都使用字符串。 How will that handle negativ number? 如何处理负数? Float numbers? 浮点数? My solution uses only Mathematical functions and and works for all numbers (i think). 我的解决方案只使用数学函数,并适用于所有数字(我认为)。

http://jsfiddle.net/xBVjB/7/ http://jsfiddle.net/xBVjB/7/

See link for function and some testcases :) 查看功能链接和一些测试用例:)

Cheers 干杯

function A(a){var b=Math.abs(a);return((b+'')[0]/1+1)*Math.pow(10,(b+'').length-1)*(a<0?-1:1)}

Here is my answer manipulating a string. 这是我操纵字符串的答案。 It handles negatives, but I am not sure how the OP wants negatives rounded up/down. 它处理负面因素,但我不确定OP如何要求负面向上/向下舍入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM