简体   繁体   English

Javascript toFixed() 没有尾随零

[英]Javascript toFixed() no trailing zeros

I'm tired and this is maths.我累了,这是数学。 Should be fairly simple, and good chance I get it while typing this out.应该相当简单,我很有可能在打字时得到它。

I have a function, let's call it roundNumber我有一个 function,我们称之为 roundNumber

function roundNumber(value){
    return value.toFixed(3);
}

But I want to round to 3 decimal, unless the succeeding digits are 0. Desired result:但我想四舍五入到小数点后 3,除非后面的数字是 0。期望的结果:

roundNumber(1/3) //Should output 0.333
roundNumber(1/2) //Should output 0.5, NOT 0.500
roundNumber(1/8) //Should output 0.125
roundNumber(1/4) //Should output 0.25

Best way to do this?最好的方法?

To do what you require you can convert the string result of toFixed() back to a numerical value.要执行您需要的操作,您可以将toFixed()的字符串结果转换回数值。

The example below uses the + unary operator to do this, but Number() or parseFloat() would work just as well.下面的示例使用+一元运算符来执行此操作,但Number()parseFloat()也可以正常工作。

 function roundNumber(value) { return +value.toFixed(3); } console.log(roundNumber(1 / 3)) //Should output 0.333 console.log(roundNumber(1 / 2)) //Should output 0.5, NOT 0.500 console.log(roundNumber(1 / 8)) //Should output 0.125 console.log(roundNumber(1 / 4)) //Should output 0.25

First off: What the function does is not just rounding.首先:function 所做的不仅仅是四舍五入。 It converts a number to a string (doing some rounding along the way).它将数字转换为字符串(沿途进行一些舍入)。

If you really want a string, your best bet is probably to trim off trailing zeros that don't have a .如果你真的想要一个字符串,你最好的办法可能是修剪掉没有. in front of them:在他们面前:

return value.toFixed(3).replace(/([^.])0+$/, "$1");

Live Example:现场示例:

 function roundNumber(value) { return value.toFixed(3).replace(/([^.])0+$/, "$1"); } console.log(roundNumber(1/3)); //Should output 0.333 console.log(roundNumber(1/2)); //Should output 0.5, NOT 0.500 console.log(roundNumber(1/8)); //Should output 0.125 console.log(roundNumber(1/4)); //Should output 0.25

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

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