Nick T
Nick T

Reputation: 101

Postgres - Only sometimes want to display a digit to the left of decimal separator

Right now I am using numeric(4,3) data type to represent a percentage in decimal form (ex. 57.2% = .572). The problem is, when I save it's ALWAYS displaying these decimals with a digit to the left of the decimal separator. So in other words it is displaying as 0.572 when I want it to display as .572 .However, there are occasions when I want a digit to the left of the separator(like when displaying the 1.000 ,meaning 100%).

What is the data type that I should use to accomplish this? Any help would be appreciated. Thanks.

Upvotes: 0

Views: 320

Answers (2)

McNets
McNets

Reputation: 10807

SELECT to_char(0.157, '0.99%');
| to_char |
| :------ |
|  0.16%  |
SELECT to_char(0.157, '9.99%');
| to_char |
| :------ |
|   .16%  |

dbfiddle here

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1269633

Numbers are numbers. If you want to format them in a particular way, you can use to_char(). This is particularly true if you want to format them in different ways under different circumstances.

The documentation covers the situations you describe.

Upvotes: 2

Related Questions