-1

I need to display a price in a format like

7
70 
700
700 000
70 000
700 000
7 000 000 etc

The problem is that I receive the price from json file, so it's always a string.

What I want is to convert that price string into the desired format by RegEx.

  1. We invert the price 7000000 = 0000007
  2. We put a whitespace after 3rd character in the inverted string 000 000 7
  3. Then we invert the string again and get a normal price format 7 000 000

Is it possible for json data and perhaps there is a more correct way to go? Didn't find any working examples.

Alexandr Belov
  • 1,804
  • 9
  • 30
  • 43
  • You should check out http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript. – Piyush Jan 25 '17 at 18:09
  • "*The problem is that I receive the price from json file, so it's always a string.*" This is incorrect. JSON [supports numbers](http://www.json.org/). – JDB Jan 25 '17 at 18:10

1 Answers1

6

You could use a regex to do so:

function numberWithSpaces(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}

Or convert it to a number then use num.toLocaleString(), which will automatically convert it.

Taken from Adding space between numbers?

Community
  • 1
  • 1
Antony
  • 1,253
  • 11
  • 19