I have a table like this:
| size |
|---------------|
| 2880129015916 |
| 2560 |
| 0 |
| 91570752 |
| 8192 |
| 21037156 |
and I want to display the values as comma separated, for example, 2880129015916 will be shown as 2,880,129,015,916.
I already saw an elegant solution on SO, Comma separating numbers without advance knowledge of number of digits in Postgres
However when I apply this to the table I get
| size | x |
|---------------|-------------------|
| 2880129015916 | 2,880,129,015,916 |
| 2560 | 2,56 |
| 0 | |
| 91570752 | 91,570,752 |
| 8192 | 8,192 |
| 21037156 | 21,037,156 |
My query was
SELECT v99.size,
rtrim(ltrim(v99.size::money::character varying::text, '$'::text), '.00'::text) AS x
FROM v99;
Any ideas why 2560 was shown as 2,56 and 0 was shown as ”?
Thanks.
2
Answers
You can use like this:
DBFiddle demo
EDIT: BTW, why your trick is faulty and not working?
You are converting size to money, which makes it like:
Then you convert it to character varying and then to text (which is redundant and the same thing, done twice).
Then you left trim the characters ‘$’ (which is already text and casting is unnecessary). They become like:
Then you do a right trim this time to "trim characters" ‘.00’ meaning you are trimming all ‘0’ and ‘.’ characters from right leaving:
Hope this makes it clear why it was not working. Simply use the formatting I showed.
data
use following query
dbfiddle