乐闻世界logo
搜索文章和话题

How to format numbers as currency strings

3个答案

1
2
3

To format numbers as currency strings, we typically follow these steps:

  1. Determine the currency unit: First, determine the currency unit, such as USD or EUR, as different currencies may have varying formats.
  2. Decimal precision: Currency values are usually formatted with two decimal places, representing cents.
  3. Thousands separator: For large amounts, a comma (or a period in some countries) is used as the thousands separator.
  4. Currency symbol: Depending on the currency, add the symbol before or after the amount, such as '$' for USD.
  5. Representation of negative numbers: For negative amounts, represent them with parentheses or a minus sign.

For example, to format the number 1234567.89 as a USD string, we do the following:

  • Determine the currency unit: USD ($)
  • Decimal precision: Keep two decimal places, i.e., '.89'
  • Thousands separator: Use a comma to separate thousands, i.e., '1,234,567.89'
  • Currency symbol: Add the USD symbol before the amount, i.e., '$1,234,567.89'
  • Representation of negative numbers: For negative, write '-$1,234,567.89' or '($1,234,567.89)'

In programming, this can be achieved in various ways. For instance, in JavaScript, we can use the Intl.NumberFormat object to format currency:

javascript
const number = 1234567.89; const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }); const formatted = formatter.format(number); // "$1,234,567.89"

In Python, we can use the built-in locale module or third-party libraries like Babel to achieve the same:

python
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') number = 1234567.89 formatted = locale.currency(number, grouping=True) # "$1,234,567.89"

These methods can achieve the goal of formatting numbers as currency strings and can be customized based on regional settings.

2024年6月29日 12:07 回复

A concise and efficient solution (works everywhere!)


(12345.67).toFixed(2).replace(/\d(?=(\d{3})+.)/g, '$&,'); // 12,345.67

The core concept of this solution is to replace the matched digits with the match itself followed by a comma, i.e., '$&,'). The matching is performed using the lookahead method. You can interpret the expression as 'match a digit if it is followed by a sequence of three-digit groups (one or more) and a dot'.

Test cases:

1 --> '1.00' 12 --> '12.00' 123 --> '123.00' 1234 --> '1,234.00' 12345 --> '12,345.00' 123456 --> '123,456.00' 1234567 --> '1,234,567.00' 12345.67 --> '12,345.67'

Demo: http://jsfiddle.net/hAfMM/9571/


Extended short solution

You can extend the prototype of the Number object to add support for arbitrary decimal places [0 .. n] and group size [0 .. x]:

javascript
/** * Number.prototype.format(n, x) * * @param integer n: decimal length * @param integer x: group size */ Number.prototype.format = function(n, x) { var re = '\d(?=(\d{' + (x || 3) + '})+' + (n > 0 ? '\.' : '$') + ')'; return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,'); }; 1234..format(); // '1,234' 12345..format(2); // '12,345.00' 123456.7.format(3, 2); // '12,34,56.700' 123456.789.format(2, 4); // '12,3456.79'

Demo/Test: http://jsfiddle.net/hAfMM/435/


Super extended solution

In this super extended version, you can configure different delimiter types:

javascript
/** * Number.prototype.format(n, x, s, c) * * @param integer n: decimal length * @param integer x: whole part length * @param mixed s: sections delimiter * @param mixed c: decimal delimiter */ Number.prototype.format = function(n, x, s, c) { var re = '\d(?=(\d{' + (x || 3) + '})+' + (n > 0 ? '\D' : '$') + ')', num = this.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); }; 12345678.9.format(2, 3, '.', ','); // '12.345.678,90' 123456.789.format(4, 4, ' ', ':'); // '12 3456:7890' 12345678.9.format(0, 3, '-'); // '12-345-679'

Demo/Test: http://jsfiddle.net/hAfMM/612/

2024年6月29日 12:07 回复

Let's examine the JavaScript Number object to see if it can assist you.

  • toLocaleString() formats numbers with locale-specific thousand separators.
  • toFixed() rounds numbers to a specified number of decimal places.

To use both methods together, you must convert the type back to a number since they both output strings.

Example:

javascript
Number((someNumber).toFixed(1)).toLocaleString()

Edit You can directly use toLocaleString without re-converting to a number:

javascript
someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});

Multiple Numbers

If you frequently need to format numbers similarly, you can create a specific object for reuse. For example, in German (Swiss):

javascript
const money = new Intl.NumberFormat('de-CH', { style: 'currency', currency: 'CHF' }); const percent = new Intl.NumberFormat('de-CH', { style: 'percent', maximumFractionDigits: 1, signDisplay: "always"});

Can be used as:

javascript
money.format(1234.50); // output CHF 1'234.50 percent.format(0.083); // output +8.3%

Quite elegant.

2024年6月29日 12:07 回复

你的答案