简体   繁体   English

JavaScript显示货币,不取整

[英]Javascript display currency without rounding

I am displaying currency values in javascript, I want to display $ with every value and I also want , (comma) for thousands but I don't want rounding of digits after decimal point and I also don't have a fixed limit of how many digits would be after decimal point. 我在javascript中显示货币值,我想显示每个值都有$,并且我也想显示(逗号)千位,但是我不想在小数点后四舍五入,而且我也没有固定的限制小数点后将有很多数字。

It is for en-AU 适用于en-AU

for example 例如

45000 -> $45,000 45000-> $ 45,000

3.6987 -> $3.6987 3.6987-> $ 3.6987

3 -> $3 3-> $ 3

4.00 -> $4.00 4.00-> 4.00美元

Is there any built-in JavaScript method or library can help to achieve this? 有没有内置的JavaScript方法或库可以帮助实现这一目标?

You can use toLocaleString to add the commas to the number. 您可以使用toLocaleString将逗号添加到数字中。

var number = 45000;
var formatted = '$' + number.toLocaleString(); // $45,000

number = 500999.12345;
formatted = '$' + number.toLocaleString(); // $500,999.12345

EDIT: To prevent rounding, use minimumFractionDigits option: 编辑:为防止舍入,请使用minimumFractionDigits选项:

number.toLocaleString(undefined, { minimumFractionDigits: 20 });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Related to this question . 这个问题有关

I Suggest to use Intl.NumberFormat 我建议使用Intl.NumberFormat

var formatter = new Intl.NumberFormat('en-US', {
   style: 'currency',
   currency: 'USD',
   minimumFractionDigits: 2,      
});

formatter.format(3242); /* $3,242.00 */

You can config your FractionDigits and even your currency sign : 您可以配置您的FractionDigits甚至您的货币符号:

var formatter = new Intl.NumberFormat('en-US', {
   style: 'currency',
   currency: 'GBP',
   minimumFractionDigits: 4,      
});

formatter.format(3242); /* £3,242.0000 */

UPDATE : 更新:

if you can't fixed your fraction digits you can use maximumFractionDigits and give it an amount of 20 and also give minimumFractionDigits value of 0 : 如果您无法固定小数位数,则可以使用maximumFractionDigits并为其设置20的值,还可以将minimumFractionDigits值设置为0:

var formatter = new Intl.NumberFormat('en-US', {
   style: 'currency',
   currency: 'GBP',
   minimumFractionDigits: 0,
   maximumFractionDigits: 20,
});

formatter.format(3242.5454); /* £3,242.5454 */

看一看accounting.js ,它具有以货币格式格式化值的强大功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM