我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

要在小数位置pos(不包括小数)舍入,请执行Math.rround(num*Math.pow(10,pos))/Math.pow(1,pos

var控制台={日志:函数{document.getElementById(“控制台”).innerHTML+=s+“<br/>”}}var roundDecimals=函数(num,pos){return(Math.round(num*Math.pow(10,pos))/Math.pop(10,pos));}//https://en.wikipedia.org/wiki/Pivar pi=3.14159265358979323846264338327950288419716939937510;对于(var i=2;i<15;i++)console.log(“pi=”+roundDecimals(pi,i));对于(var i=15;i>=0;--i)console.log(“pi=”+roundDecimals(pi,i));<div id=“console”/>

其他回答

请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。

var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));

2017只需使用本机代码.toFixed()

number = 1.2345;
number.toFixed(2) // "1.23"

如果您需要严格要求并在需要时添加数字,可以使用替换

number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');

我只是想根据前面提到的答案分享我的方法:

让我们创建一个函数,将任何给定的数值舍入到给定的小数位数:

function roundWDecimals(n, decimals) {
    if (!isNaN(parseFloat(n)) && isFinite(n)) {
        if (typeof(decimals) == typeof(undefined)) {
            decimals = 0;
        }
        var decimalPower = Math.pow(10, decimals);
        return Math.round(parseFloat(n) * decimalPower) / decimalPower;
    }
    return NaN;
}

并为数字原型引入一种新的“舍入”方法:

Object.defineProperty(Number.prototype, 'round', {
    enumerable: false,
    value: function(decimals) {
        return roundWDecimals(this, decimals);
    }
});

您可以测试它:

函数舍入WDecimals(n,小数){if(!isNaN(parseFloat(n))&&isFinite(n){if(typeof(小数)==typeof(未定义)){小数=0;}var decimalPower=数学.pow(10,小数);return Math.round(parseFloat(n)*decimalPower)/decimalPower;}返回NaN;}Object.defineProperty(Number.prototype,'round'{可枚举:false,值:函数(小数){返回舍入WDecimals(this,小数);}});var舍入=[{num:10,小数:2},{num:1.7777777,小数:2},{num:9.1,小数:2},{num:55.55,小数:1},{num:55.549,小数:1},{num:55,小数:0},{num:54.9,小数:0},{num:-55.55,小数:1},{num:-55.551,小数:1},{num:-55,小数:0},{num:1.005,小数:2},{num:1.005,小数:2},{num:198000000007,小数:2},],table='<table border=“1”><tr><th>Num</th><th>小数</th><th>结果</th></tr>';$.each(roundables,function(){表+='<tr>'+“<td>”+此.num+“</td>”+“<td>”+此小数+“</td>”+'<td>'+this.num.round(this.decimals)+'</td>'+'</tr>';});table+=“</table>”;$('.results').append(表);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><div class=“results”></div>

我尝试了自己的代码。试试看:

function AmountDispalyFormat(value) {
    value = value.toFixed(3);
    var amount = value.toString().split('.');
    var result = 0;
    if (amount.length > 1) {
        var secondValue = parseInt(amount[1].toString().slice(0, 2));
        if (amount[1].toString().length > 2) {
            if (parseInt(amount[1].toString().slice(2, 3)) > 4) {
                secondValue++;
                if (secondValue == 100) {
                    amount[0] = parseInt(amount[0]) + 1;
                    secondValue = 0;
                }
            }
        }

        if (secondValue.toString().length == 1) {
            secondValue = "0" + secondValue;
        }
        result = parseFloat(amount[0] + "." + secondValue);
    } else {
        result = parseFloat(amount);
    }
    return result;
}

您也可以重写Math.round函数来进行舍入校正,并为小数添加一个参数,并使用它,如:Math.round(Number,decimals)。请记住,这将覆盖内置组件Math.round,并为其提供另一个属性,而不是原始属性。

var round = Math.round;
Math.round = function (value, decimals) {
  decimals = decimals || 0;
  return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}

然后你可以这样简单地使用它:

Math.round(1.005, 2);

https://jsfiddle.net/k5tpq3pd/3/