在javascript中将数字转换为带有两位小数的逗号分隔格式 [英] Convert numbers into comma separated format with two decimals in javascript

查看:42
本文介绍了在javascript中将数字转换为带有两位小数的逗号分隔格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字转换为逗号分隔的格式,javascript 中的每个数字都有两个小数位:

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

我的代码:

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

此代码不显示整数的两位小数 (.00).

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

感谢您的回答,谢谢.

推荐答案

您可以使用 toLocaleStringminimumFractionDigits 选项 功能.

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
});

您甚至可以删除 parseFloat、toFixed 和 Number 函数的用法,如果这不用于某些逻辑而不是显示最多 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.

这篇关于在javascript中将数字转换为带有两位小数的逗号分隔格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆