如何格式化Javascript中的float?

JavaScript

十三西门

2020-03-16

在JavaScript中,从浮点数转换为字符串时,小数点后仅能获得2位数字吗?例如,用0.34代替0.3445434。

第1708篇《如何格式化Javascript中的float?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
Sam小哥 2020.03.16

The key here I guess is to round up correctly first, then you can convert it to String.

function roundOf(n, p) {
    const n1 = n * Math.pow(10, p + 1);
    const n2 = Math.floor(n1 / 10);
    if (n1 >= (n2 * 10 + 5)) {
        return (n2 + 1) / Math.pow(10, p);
    }
    return n2 / Math.pow(10, p);
}

// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34

Now you can safely format this value with toFixed(p). So with your specific case:

roundOf(0.3445434, 2).toFixed(2); // 0.34
小哥蛋蛋 2020.03.16

所有这些使用乘法器的解决方案都存在问题。不幸的是,kyky和Christoph的解决方案都是错误的。

请测试您的代码551.175的两位小数位-它会四舍五入为551.17,而它应该是551.18但是,如果您测试前。451.175可以-451.18。因此,乍一看很难发现此错误。

问题在于相乘:尝试551.175 * 100 = 55117.49999999999(ups!)

所以我的想法是在使用Math.round()之前,先用toFixed()处理它;

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

要注意的另一个问题是,toFixed()在数字末尾可能会产生不必要的零。例如:

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

这个想法是使用以下命令清理输出RegExp

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

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"
达蒙阿飞斯丁 2020.03.16
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
米亚ItachiL 2020.03.16

有一些函数可以四舍五入。例如:

var x = 5.0364342423;
print(x.toFixed(2));

将打印5.04。

编辑: 小提琴

樱西里猴子 2020.03.16
var result = Math.round(original*100)/100;

具体细节,以防代码不言自明。

编辑:...或toFixed按照TimBüthe的建议使用忘了那个,谢谢(和赞扬):)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android