如何在字符串中的数字中添加逗号

时间:2020-02-05 10:33:53

标签: javascript

所以我知道如何在数字(toLocaleString。())上添加逗号,并且此函数需要整数或十进制值作为参数。我需要2位十进制值的结果。它会运行并返回正确的数据,但我希望将小数位数固定为如下所示的2位数字

var num = 66666.7
console.log("original", num)
console.log("with comma", num.toLocaleString())
console.log("with 2 digit fixed", num.toFixed(2))
console.log("not working--", (num.toFixed(2)).toLocaleString())
console.log("error--", (num.toLocaleString()).toFixed(2))
它不适用于toFixed()值 请提出任何建议!

3 个答案:

答案 0 :(得分:4)

您可以在选项中指定精确的小数位数,这是toLocaleString()中的第二个参数

const number = 24242324.5754;

number.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
})

// result is: 24,242,324.58

另请参见MDN文档here

minimumFractionDigits

要使用的最小小数位数。 可能的值为0到20;否则为0。缺省数字和 格式化百分比为

maximumFractionDigits

要使用的最大小数位数。 可能的值为0到20;否则为0。普通号码的默认值 格式是minimumFractionDigits和3

中的较大者

答案 1 :(得分:1)

我认为toFixed()正在将浮点数更改为字符串。

num = 66666.7;
num = parseFloat(num.toFixed(2))
console.log(num.toLocaleString())

以下解决方案应该可以正常工作。

编辑-为此,还有另一种解决方案

(Math.round(num * 100) / 100).toFixed(2);

答案 2 :(得分:1)

toFixed()方法返回一个字符串,但是toLocaleString()方法需要一个数字,因此,在将toFixed()方法与parseFloat()函数一起使用后,只需将字符串转换为数字即可,然后在其上使用toLocaleString()方法。

但是,请注意,由于0方法会删除小数点右边的所有前导零,因此您必须手动附加前导parseFloat()

在另一个堆栈溢出线程上检查此particular answer,该线程解释了parseFloat()方法删除小数点后的前导零的原因。


var num = 66666.7
var parsedNum = (""+num).split('.')[1].length > 1 ?
    parseFloat(num.toFixed(2)).toLocaleString() : 
    parseFloat(num.toFixed(2)).toLocaleString() + '0';

console.log("original", num)
console.log("with comma", num.toLocaleString())
console.log("with 2 digit fixed", num.toFixed(2))
console.log("now working--", parsedNum)

相关问题