如何在javascript中格式化浮点数?

本文翻译自:How to format a float in javascript?

In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? 在JavaScript中,当从float转换为字符串时,如何在小数点后只获得2位数? For example, 0.34 instead of 0.3445434. 例如,0.34而不是0.3445434。


#1楼

参考:https://stackoom.com/question/2m6M/如何在javascript中格式化浮点数


#2楼

There is a problem with all those solutions floating around using multipliers. 使用乘数的所有解决方案都存在问题。 Both kkyy and Christoph's solutions are wrong unfortunately. 不幸的是,kkyy和Christoph的解决方案都是错误的。

Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! 请测试您的代码为551.175,带有2位小数 - 它将舍入到551.17,而它应该是551.18 But if you test for ex. 但如果你测试前。 451.175 it will be ok - 451.18. 451.175就可以了 - 451.18。 So it's difficult to spot this error at a first glance. 因此,乍一看很难发现这个错误。

The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!) 问题在于倍增:尝试551.175 * 100 = 55117.49999999999(ups!)

So my idea is to treat it with toFixed() before using Math.round(); 所以我的想法是在使用Math.round()之前用toFixed()对待它;

function roundFix(number, precision)
{
    var multi = Math.pow(10, precision);
    return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}

#3楼

One more problem to be aware of, is that toFixed() can produce unnecessary zeros at the end of the number. 还有一个需要注意的问题是, toFixed()会在数字末尾产生不必要的零。 For example: 例如:

var x=(23-7.37)
x
15.629999999999999
x.toFixed(6)
"15.630000"

The idea is to clean up the output using a RegExp : 我们的想法是使用RegExp清理输出:

function humanize(x){
  return x.toFixed(6).replace(/\.?0*$/,'');
}

The RegExp matches the trailing zeros (and optionally the decimal point) to make sure it looks good for integers as well. RegExp匹配尾随零(以及可选的小数点)以确保它看起来也适用于整数。

humanize(23-7.37)
"15.63"
humanize(1200)
"1200"
humanize(1200.03)
"1200.03"
humanize(3/4)
"0.75"
humanize(4/3)
"1.333333"

#4楼

There is no way to avoid inconsistent rounding for prices with x.xx5 as actual value using either multiplication or division. 使用乘法或除法无法避免x.xx5作为实际值的价格不一致舍入。 If you need to calculate correct prices client-side you should keep all amounts in cents. 如果您需要计算客户端的正确价格,您应该将所有金额保持在美分。 This is due to the nature of the internal representation of numeric values in JavaScript. 这是由于JavaScript中数值的内部表示的性质。 Notice that Excel suffers from the same problems so most people wouldn't notice the small errors caused by this phenomen. 请注意,Excel遇到了同样的问题,因此大多数人都不会注意到这个现象引起的小错误。 However errors may accumulate whenever you add up a lot of calculated values, there is a whole theory around this involving the order of calculations and other methods to minimize the error in the final result. 但是,每当您将大量计算值相加时,错误可能会累积,有一个完整的理论涉及计算顺序和其他方法以最小化最终结果中的错误。 To emphasize on the problems with decimal values, please note that 0.1 + 0.2 is not exactly equal to 0.3 in JavaScript, while 1 + 2 is equal to 3. 为了强调十进制值的问题,请注意在JavaScript中0.1 + 0.2并不完全等于0.3,而1 + 2等于3。


#5楼

/** don't spend 5 minutes, use my code **/
function prettyFloat(x,nbDec) { 
    if (!nbDec) nbDec = 100;
    var a = Math.abs(x);
    var e = Math.floor(a);
    var d = Math.round((a-e)*nbDec); if (d == nbDec) { d=0; e++; }
    var signStr = (x<0) ? "-" : " ";
    var decStr = d.toString(); var tmp = 10; while(tmp<nbDec && d*tmp < nbDec) {decStr = "0"+decStr; tmp*=10;}
    var eStr = e.toString();
    return signStr+eStr+"."+decStr;
}

prettyFloat(0);      //  "0.00"
prettyFloat(-1);     // "-1.00"
prettyFloat(-0.999); // "-1.00"
prettyFloat(0.5);    //  "0.50"

#6楼

You can try this if you don't want to use rounding. 如果您不想使用舍入,可以尝试此操作。

 function myFunction(str) { str = str.toString().split('.'); var res = str[1].slice(0, 2); document.getElementById("demo").innerHTML = str[0]+'.'+res; } myFunction(12.234556); 
 <div id="demo"></div> 

str.toString().split('.') will convert your float number into string then split it by '.' str.toString().split('.')会将您的浮点数转换为字符串,然后将其拆分为'。'

Resulting variables will an array with two string type elements, the first element will be 12 and the second element will be 234556 结果变量将是一个包含两个字符串类型元素的数组,第一个元素将是12,第二个元素将是234556

str[1].slice(0, 2) will slice your second (234556) string into first two char which is 23 str[1].slice(0, 2)会将你的第二个(234556)字符串切成前两个字符,即23

Then just concatenating first and resulting string through str[0]+'.'+res 然后通过str[0]+'.'+res连接第一个和结果字符串

Hope this will help 希望这会有所帮助

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值