It is a very common problem to convert ordinary numbers to a string of numbers in the thousand separator format, where the rule is that the integer parts of a number are grouped in three digits, separated by a comma. The decimal part is not divided into sections. Example: 19,351,235.23 there are several common implementations.

Method 1 uses the built-in JS functiontoLocaleString

Syntax: numObj. ToLocaleString ([locales [, options]])

The toLocaleString() method returns the locale-specific representation string for this number.

var a=1234567894532; Var b = 673439.4542; console.log(a.toLocaleString()); / / "1234567894532" the console. The log (b.t oLocaleString ()); // "673,439.454"Copy the code

Note that this function returns a string formatted with the default locale and default options when there is no basic use of the locale, so there may be some differences between locale numbers. It is best to make sure that the locales parameter specifies the language to use. Note: I tested the environment in which the decimals were rounded to only three places.

Used method of twoRegular expression 和 replacefunction

The replace syntax: STR. Replace (regexp | substr, newSubStr | function)

Var data = 123456789.12345 var b = data.tofixed (2).replace(/(\d)(? =(\d{3})+\.) /g, '$1,'); The console. The log (b) / / 123456789.12Copy the code

Method three js hard write

The idea is to convert a number into an array of characters, loop through the array, add a comma for every three digits, and merge it into a string. Because delimiters are added backwards in order: for example, 1234567 was added to 1,234,567 instead of 123,456,7, it is convenient to reverse the array first, and then reverse it back to the normal order. Note that if numbers have decimals, separate the decimals. Code, this method is not recommended, so don’t go into here, if want to use this method, can refer to the article = > www.jianshu.com/p/928c68f92…

If this article is helpful to you, thank you for your careful heart, your support is my motivation to continue to create!