'How to right-align a column when selecting data?
A school assignment I'm working on says to format a decimal(14,0) column "as currency [US$xxx,xxx] and right justified [all the commas line up vertically]."
I can select the data in the correct format using this:
CONCAT("US$", FORMAT(theColumn, 0))
But the data is not right justified. I've been searching and searching and simply haven't been able to find any way to right justify the output.
I did find an answer on here that shows how to do it if the column is a string type and has a fixed width, but I can't find a way to right justify the output for a decimal data type. Is it possible?
EDIT:
MySQL returns data left justified, like this:
US$18,100,000,000
US$130,100,000,000
US$1,200,000,000
I want to select it right justified, like this:
US$18,100,000,000
US$130,100,000,000
US$1,200,000,000
Solution 1:[1]
I think you want
select lpad(column_name,x,' ') from table_name;
where x is the number of places you want that value you fill (so say 8 places)
Solution 2:[2]
I would have done:
LPAD(CONCAT("US$", FORMAT(theColumn, 0)),20,' ')
What this does is present the output in a column of 20 characters, padding ' ' to the left of values.
Solution 3:[3]
Another way is:
RIGHT(CONCAT(" US$", theColumn), 17)
Basically, prefix your_field with enough spaces to fill your display column, then take the right most characters from that. So if your display column is 17 characters, prefix your_field with (at least) 17 spaces/"US$" then take the right most 17 characters of that string. 17 is the 14,0 plus the 3 characters in "US$".
Nope, I don't like it either, especially in this day and age, but it does work. I suppose DB engines don't have something sophisticated to do this is the philosophy that the DB is the "Model" and not the "View".
Solution 4:[4]
Use CONCAT with div right align. Example:
CONCAT("<div style='text-align:right',(FORMAT(theColumn, 0))
This is working with MySQL.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Outsider |
| Solution 2 | Kyll |
| Solution 3 | user3481644 |
| Solution 4 | ahuemmer |
