Number format with comma and decimal points
我试过使用Number(x).toLocaleString(),但这只给了我10000。
当我使用parseFloat(row.profit).toFixed(2)时,它给了我10000.00。我试着把parseFloat(Number(row.profit)toLocaleString()).toFixed(2)结合起来,但没有给我期望的输出,应该是10000.00。我怎样才能做到这一点?
- Look at the specs for Tolocalesting.是一个选项,你可以选择。
- 好吧,So you did't ask about money,but if you ignore the dollar sign the linked duplicate is asking the same thing about the commas and dec马尔s,and e.g.,this answer does it with a fairly short function.
- Consider the answers to how to format numbers using Javascript?,which uses tolocalesting to determine whether to use,"for those usands and."For Decima or Vice Versa.
- @Nnnnn the link answer is delete please check
- @Guradio-Sorry,I accidentally double-pasted the URL in my link.编辑了我以前对这一问题的评论。
如果您的区域设置字符串中是否存在.,您可以通过测试来使用快速黑客:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function localeFormat(x) {
var num = Number(x).toLocaleString();
if (num.indexOf("/.") > 0) {
num +=".00";
}else{
var n = parseFloat(x).toFixed(2).toString();
num = Number(n).toLocaleString();
}
return num;
}
var strs = ["10000","10000.45","10000.45768"];
for(var i = 0; i < strs.length; i++){
console.log(strs[i] +" ->" + localeFormat(strs[i]));
} |