Convert numbers into comma separated format with two decimals in javascript

99封情书 提交于 2019-12-23 10:10:14

问题


I am trying to convert numbers into comma separated format with two decimal places for each and every number in javascript:

My code:

Number(parseFloat(n).toFixed(2)).toLocaleString('en');

This code doesn't show two decimal places (.00) for whole numbers.

I am expecting following results for a set of numbers:

10000 => 100,00.00
123233.12 => 123,233.12
300000.5  => 300,000.50

Appreciate your answer, thanks.


回答1:


You can use the minimumFractionDigits option of the toLocaleString function.

// result 3,000.00
Number(parseFloat(3000).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

// result 123,233.12
Number(parseFloat(123233.12).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

You can even remove the parseFloat,toFixed and Number function usage as well, if this is not used for some logic other than displaying the decimal value up to 2 digits.



来源:https://stackoverflow.com/questions/38462619/convert-numbers-into-comma-separated-format-with-two-decimals-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!