Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousand separator Oracle

Tags:

sql

oracle

I can use this to get desired format:

SELECT TO_CHAR(12345,'99G999') "Amount" FROM DUAL;
SELECT TO_CHAR(123456,'999G999') "Amount" FROM DUAL;
SELECT TO_CHAR(1234567,'9G999G999') "Amount" FROM DUAL; 

Is there a method where you don't have to check the length like this?:

select case
when length(my_number) = 5 then TO_CHAR(my_number,'99G999')
when length(my_number) = 6 then TO_CHAR(my_number,'999G999')
like image 500
Johnny Gunn Avatar asked Feb 28 '19 13:02

Johnny Gunn


People also ask

How do you round to 2 decimal places in Oracle?

SELECT ROUND(-4.535,2) FROM dual; Here is the result. The above statement will round the given number -4.535 up to 2 decimal places.

What is Nls_numeric_characters?

NLS_NUMERIC_CHARACTERS specifies the characters to use as the group separator and decimal character. It overrides those characters defined implicitly by NLS_TERRITORY . The group separator separates integer groups (that is, thousands, millions, billions, and so on).


1 Answers

Using 9 in the model (as opposed to 0) means you don't get leading zeros, so you can use the same model for all of those:

SELECT TO_CHAR(12345,'9G999G999') "Amount" FROM DUAL;

Amount    
----------
    12,345

SELECT TO_CHAR(123456,'9G999G999') "Amount" FROM DUAL;

Amount    
----------
   123,456

SELECT TO_CHAR(1234567,'9G999G999') "Amount" FROM DUAL; 

Amount    
----------
 1,234,567

You just need enough 9s (and Gs) for the longest value you expect to handle.

If you don't want the leading spaces - including the one that's there in all of those as a placeholder for a potential minus sign for negative values - you can add the FM 'fill mode' format model modifier:

SELECT TO_CHAR(12345,'FM999G999G999G999') "Amount" FROM DUAL;

Amount          
----------------
12,345

SELECT TO_CHAR(123456,'FM999G999G999G999') "Amount" FROM DUAL;

Amount          
----------------
123,456

SELECT TO_CHAR(1234567,'FM999G999G999G999') "Amount" FROM DUAL; 

Amount          
----------------
1,234,567
like image 88
Alex Poole Avatar answered Oct 24 '22 10:10

Alex Poole