0

I have an int field in a MySQL database that is progressively going up every time a user of the database performs a specific action so it's going up in increments of 1.

When displaying this on a php page, I want it to display this value as 0,000,001 rather than it's raw data of just 1.

How do I format the number to display like this? I've never had to do it before, so I'm bewildered.

2
  • 1
    Convert it to a string and pad the beginning with however many 0s and commas you need.
    – durbnpoisn
    Jan 14, 2016 at 18:08
  • A more specific title. Trim the question down to just the facts. Jan 14, 2016 at 19:14

2 Answers 2

1

Something like this should work:

SELECT INSERT(INSERT(LPAD([value], 7, '0'), 5, 0, ','), 2, 0, ',')
FROM ....

LPAD returns a string of length 7, with leading 0's. If [value] is longer than 7 it will be truncated (from the right); so '12345678' becomes '1234567'.

The two INSERT calls insert the commas.

Edit: Changed the 1's to 0's; apparently they effectively made it a "replace" rather than an "insert".

I'd suggest doing this in code though, instead of a query, if you can.

2
  • Will this remove 0's as the actual data gets bigger or will it always keep the same amount of 0's in front of the original number? Jan 14, 2016 at 18:27
  • @Equinox04 The final string's length remains constant; I added some explanation above the 'Edit', but below the query fragment. If you're worried about going to "100 million", you'll probably need some IF()'s or CASE's to adjust comma positions for longer strings.
    – Uueerdo
    Jan 14, 2016 at 19:06
1

If you would rather do it in the php, something like:

$pretty = substr(number_format(10000000 + $counter), 1);

this will work as long as counter never exceeds 9,999,999.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.