Search code examples
sqlpostgresqlnumber-formatting

Remove all but two trailing zeros AND thousand separator


Postgres Version 11.7

I am trying to remove trailing zeros beyond two decimal places, while also adding thousand separator to my result set.

Example 1 produces the desired result; all trailing zeros were removed:

SELECT to_char(54354.0010, 'FM99 999 999 990.999999'); --> returns 54 354.001

Example 2 illustrates the problem:

SELECT to_char(54354.0000, 'FM99 999 999 990.999999'); --> returns 54 354.

In Example 2 all zeroes after the decimal are removed.
But the desired result would be:

54 354.00

The result should always have a minimum of two decimal places, regardless whether they are zero or not.


Solution

  • This produces your desired result:

    SELECT to_char(54354.0000, 'FM99 999 999 990.009999')
    

    Two 0 instead of 9 after the decimal point.
    The manual:

    9 digit position (can be dropped if insignificant)
    0 digit position (will not be dropped, even if insignificant)