Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I did:</p> <pre><code>const numberWithCommas = (x) =&gt; { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } </code></pre> <p>This is all you really need to know.</p> <p>@Neils Bom asked how the regex works. My explanation is sort of long. It won't fit in the comments and I don't know where else to put it so I am doing it here. If anyone has any other suggestions for where to put it, please let me know.</p> <p>The regex uses 2 lookahead assertions: a positive one to look for any point in the string that has a multiple of 3 digits in a row after it, and a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.</p> <p>For example, if you pass it "123456789.01", the positive assertion will match every spot to the left of the 7 (since "789" is a multiple of 3 digits, "678" is a multiple of 3 digits, "567", etc.). The negative assertion checks that the multiple of 3 digits does not have any digits after it. "789" has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. "678" is a multiple of 3 digits but it has a "9" after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for "567". "456789" is 6 digits, which is a multiple of 3, so a comma goes before that. "345678" is a multiple of 3, but it has a "9" after it, so no comma goes there. And so on. The "\B" keeps the regex from putting a comma at the beginning of the string.</p> <p>@neu-rah mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:</p> <pre><code>const numberWithCommas = (x) =&gt; { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload