tags:

views:

77

answers:

3

I have a 'price' variable that contains some integer number from a MySQL database.

I want to check how many numbers the 'price' variable contains, and add a space in the variable depending on how many numbers. See below:

Example:

If 'price' is 150000 I would like the output to be 150 000 (notice the space). OR, if it is 19000 I would like it to output 19 000...

How would you do this the easiest way?

+7  A: 

The easiest way is to use number_format():

$str = number_format($number, 0, '.', ' ');
Greg
Will this work on INT? I cant get it to work, it does display the price, but not the space ex 190000 is the same after formatting it
Camran
It doesn't matter if the data is INT in the database; PHP initially sees all data from db queries as strings, then converts implicitly as needed. Greg's code should work. How are you presenting the number_format() return to the browser?
GZipp
+2  A: 

Use the number_format function to format a number:

number_format($number, 0, '.', ' ')
Gumbo
+2  A: 

If what you are trying to do is format the number with grouped thousands and a space as the thousand separator, use this.

number_format($number, 2, '.', ' ');

Kailash Badu
Will this work on INT? I cant get it to work, it does display the price, but not the spaceex 190000 is the same after formatting it...
Camran
This will work with both int and float. I applied the above function 190000 just a while ago, and correctly displayed '190 000.00'. It's very likely you are doing it wrong. If you care to post the entire block of code, it'll be easier to catch the bug. On another note, remember that you can adjust the second parameter of the above function to specify desired number of digits after the decimal point. So if the number in question is strictly an integer, you might just want to make the second parameter '0' instead of current '2'.
Kailash Badu