在 JavaScript 中格式化货币删除 .00 [英] Format currency in JavaScript removing .00

查看:24
本文介绍了在 JavaScript 中格式化货币删除 .00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码格式化数字以显示为货币值:

I am currently formatting numbers to display as currency values using the following code:

return symbol + value.toFixed(2).replace(/(d)(?=(d{3})+.)/g, "$1,");

其中符号是£、$ 等,值是带有许多小数位的数字.这很好用,但我现在想删除尾随 .00(如果存在).

where symbol is £,$ etc. and value is a number with many decimal places. This works great but I now want to remove trailing .00 if present.

目前我有这个输出:

1.23454 => £1.23
1 => £1.00
50.00001 => £50.00
2.5 => £2.50

我想要以下内容:

1.23454 => £1.23
1 => £1
50.00001 => £50
2.5 => £2.50

有没有比以下更清洁的方法:

Is there a cleaner way than:

var amount = symbol + value.toFixed(2).replace(/(d)(?=(d{3})+.)/g, "$1,");
return amount.replace(".00", "");

或者那个解决方案是最好的方法?

or is that solution the best way?

推荐答案

查看Intl.NumberFormat.这是一个非常方便的原生api.

Look into Intl.NumberFormat. It is a very handy native api.

let number = 1.23454;

console.log(new Intl.NumberFormat('en-GB', {
  style: 'currency',
  currency: 'GBP'
}).format(number).replace(/(.|,)00$/g, ''));
// → £1.23

这篇关于在 JavaScript 中格式化货币删除 .00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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