Original address: github.com/Daotin/fe-b…

You can also find me at:

  • Making (a star! ✨ ✨ ✨)
  • CSDN
  • Blog garden
  • The Denver nuggets
  • Wechat official account: Front-end Captain

Problem description

Today, when dealing with the formatting of a number, I encountered the following requirements:

  • You can display milliliters
  • I can show the percentage
  • Can display decimal places

As shown in the following figure, if selected, this setting will be enabled.

Percentages and decimal places are easy to solve, percentages only need to add two zeros after the source number plus a percent sign; Decimals just add zero after the decimal point. The main thing is dealing with the thousandles. Okay, let’s talk about the thousandles.

The thousandth problem

There are many processing schemes for the processing of digital thousandles, the most important ones are as follows.

Method 1: loop through

Ideas:

Convert the number to a string, then iterate over the value in reverse order, inserting one comma in every three characters until the first character is iterated.

The code is simple as follows:

function numberFormat(num) {
    let result = ' ';
    let count = 1;
    let nums = num.toString();
    for (let i = nums.length - 1; i >= 0; i--) {
        result = nums.charAt(i) + result;
        if(! (count %3) && i ! =0) { 
            result = ', ' + result; 
        }
        count++;
    }
    return result;
}

numberFormat(12345678); / / 12345678
Copy the code

Method two: re

Ideas:

The idea of this regular is to start with the first character of the number, find the number that meets the multiple of 3, and then replace the number with a number, and then continue to find……

The syntax is as follows:

let regExp = /(\d)(? =(\d{3})+$)/g;
Copy the code

Example:

String(12345678).replace(/(\d)(? =(\d{3})+$)/g."$1");
Copy the code

Explanation:

First \d denotes a number, then? =(\d{3})+ So that’s the main thing, right? =(\d{3})+ expression.

Positive prediction? =n, matches any string immediately followed by the specified string n. In combination with \d, if a number follows the string n rule, replace the matched number (say 1) with 1,.

So the question now is what is the rule for string n, which is (\d{3})+ this thing, which means that the number of numbers is a multiple of 3 (multiples 1 to n).

So the whole expression is: start with the first number, see if the number following it is a multiple of 3, if it is, replace it with a 1, and then proceed to the next number until the end.

Description:

  • gIs a modifier that represents a global match that looks for all matches instead of stopping at the first match.
  • $Is a quantifier indicating the end, e.gn$, matches any of thenIs a terminated string.
  • \dIs a metacharacter to find a number.
  • n{X}Is a quantifier that matches a string containing a sequence of X n.
  • +Matches the previous subexpression one or more times;*Matches the previous subexpression 0 or more times.?Matches the preceding subexpression 0 or 1 times, or specifies a non-greedy qualifier.
  • ? =nForward lookup, used to match any string immediately following the specified string n.
  • match()A String method that finds a match for one or more regular expressions.
  • replace()A String method that replaces substrings that match the regular expression.
  • \BIs a metacharacter that matches a non-word boundary and complements the metacharacter\bTo match word boundaries.

Method 3 (recommended 👍) : toLocaleString

According to the MDN interpretation, the number.tolocaleString () method returns the locale-specific representation string for the number.

Simple use:

var number = 3500;

console.log(number.toLocaleString()); // 3,500
Copy the code

We can call this function directly to get the result of the problem. But actually, the function does more than that, which requires analyzing its parameters.

Grammar:

numObj.toLocaleString([locales [, options]])
Copy the code
  • locales : (Optional) Indicates the country in which it is represented.
  • options: (Optional) Indicates the display style of the number (for example, should the number of decimal places be displayed? Do you want to show percentages? Etc.)

locales

Generally, the following values can be filled in:

  • en-US: United States (default value in Chinese scenarios)
  • zh-CNChina:
  • en-GB: the British
  • ko-KRSouth Korea:
  • ar-EG: the Arab
  • de-DEGermany:
  • en-INIndia:
  • ja-JPJapan:
  • .
  • (More country references: ISO Language Code Table)

options

There are a lot of properties in the Options object. Here is a list of common properties.

  • styleDefault for:decimalIs in decimal format.currencyRepresents the currency format,percentIndicates the percentage format.
  • currencyIf style is set to currency, this property sets the currency symbol (USDRepresents dollars,EURStands for euro, orCNYIs the RMB and so on, more symbols reference link:www.currency-iso.org/en/home/tab… )
  • useGrouping: Indicates whether to use the thousandth character. The default value is true
  • minimumIntegerDigits: Sets the minimum number of integers (if the number of integers is insufficient, 0 is added before it)
  • minimumFractionDigits: Sets the minimum number of small digits.

These attributes can not only meet the questions raised at the beginning of the article, but also meet the format representation of the numbers we commonly use in daily life. So we come to kangkang how to use it!

Example:

  • Set the integer part to 5 digits and the decimal part to 2 digits. Do not use the thousandth character format
Number(123).toLocaleString('zh-CN', {
    style: 'decimal'.useGrouping: false.minimumIntegerDigits : 5.minimumFractionDigits: 2
}) / / 00123.00
Copy the code
  • Sets the percentage display for two decimal places
Number(123).toLocaleString('zh-CN', {
    style: 'percent'.minimumFractionDigits: 2
}) // 12,300.00%
Copy the code
  • Setting up the euro currency
Number(123).toLocaleString('zh-CN', {
    style: 'currency'.currency: 'EUR'.minimumFractionDigits: 2
}) / / euro 123.00
Copy the code

ToLocaleString extension

In addition to the digital localization format, there are dates, arrays, objects and so on a series of localization processing, due to the limited space, no longer expand here, you can go to MDN to find relevant content, basically the usage is similar.


Finally, if there is a harvest after reading, just move your little hands and point a thumbs-up and then go, pen wick.

(event c)