最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Format currency in JavaScript removing .00 - Stack Overflow

programmeradmin1浏览0评论

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,");

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.

Currently I have this output:

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

I would like the following:

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?

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,");

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.

Currently I have this output:

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

I would like the following:

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?

Share Improve this question edited Mar 16, 2020 at 7:58 Penny Liu 17.5k5 gold badges86 silver badges108 bronze badges asked Sep 15, 2017 at 9:10 MattjeSMattjeS 1,3971 gold badge18 silver badges35 bronze badges 5
  • 1 What are your criteria for "best"? – RobG Commented Sep 15, 2017 at 9:13
  • If the value is fractional I want to display the cents/pennies, its only when the cents/pennies are 0 that I want to remove the trailing zeros. I'll update the question with some more examples – MattjeS Commented Sep 15, 2017 at 9:15
  • 1 Seems to me that symbol + value.toFixed(2).replace(/\.00/g,'') should do. – RobG Commented Sep 15, 2017 at 9:17
  • @RobG that works great thanks. – MattjeS Commented Sep 15, 2017 at 9:20
  • FYI, Number.prototype.toLocaleString be some help to you. developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – pinkfloydx33 Commented Sep 15, 2017 at 9:32
Add a ment  | 

8 Answers 8

Reset to default 5

You can get Intl.NumberFormat to round the currency to the nearest dollar (or pound or whatever) by setting maximumSignificantDigits to the number of digits in the integer part of your number

let number = 999.50;

console.log(new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumSignificantDigits: Math.trunc(Math.abs(number)).toFixed().length,
}).format(number));  // $1,000 (rounds up because 50 cents)

If you're using negative currencies, keep in mind that Intl.NumberFormat has the more sensible behavior of rounding away from zero as opposed to other JavaScript methods like Math.round. For example, Math.round(999.5) returns 1000 but Math.round(-999.5) returns -999 whereas using Intl.NumberFormat will return 1000 and -1000.

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

The native JS below will remove all trailing 0's from any number formatted as a string. NumberFormat automatically removes trailing zero's. I've chosen 20 as the maximumFractionDigits, because 20 is the max limit allowed so as long as you aren't dealing with more than 20 decimal places this will work for you in any use case.

new Intl.NumberFormat('en-IN', {
    maximumFractionDigits: 20
}).format('20.01230000') // 20.0123

Now if you are dealing with currency in Euro's meant to be viewed by a person here's what you really want.

new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'GBP' ,
    minimumFractionDigits: 0,
    minimumFractionDigits: 20
}).format('20.01530000')) // 20.02

NumberFormat doesn't just trim it rounds as well which would only make sense to do so the loss in precision leads to the least loss of accuracy possible.

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

Please change the value to test

As suggested by @RobG, I can use:

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

it can be done in a straightforward way

(parseFloat(percentage) / 100) * product.price)
    .toFixed(2)
    .toString()
    .replace('.00', '')

To remove trailing zeros in Intl.NumberFormat function I used this code:

let number = 50;
console.log(new Intl.NumberFormat('en-US', {
 style: 'currency',
 currency: 'USD',
 maximumSignificantDigits: (number + '').replace('.', '').length,
}).format(number)); // $50

To get consistent results, you need to set both minimumFractionDigits and maximumFractionDigits. Forcing the fraction digits to 0 for integer and 2 for float result in:

  • 10 to be formatted to $10
  • 10.1 to be formatted to $10.10 (instead of the default $10.1)

function formatCurrency(
  number: number,
  locale: string,
  currency: string,
) {
  const fractionDigits = Number.isInteger(number) ? 0 : 2;

  return new Intl.NumberFormat(locale, {
    style: "currency",
    currency,
    minimumFractionDigits: fractionDigits,
    maximumFractionDigits: fractionDigits
  }).format(number);
}
发布评论

评论列表(0)

  1. 暂无评论