简体   繁体   中英

In Oracle, how do I convert a number such as 1 to a string such as “1st”?

I'd like to format a number as "1st", "2nd", "4th", "9th", etc. Is there an Oracle function that will do this for me?

Assuming the value supplied is numeric, rather than DATE, you can use TO_CHAR but you have to convert the numeric value to a string, then a DATE (Julian) before ultimately formatting it:

SELECT TO_CHAR(TO_DATE('1', 'dd'), 'ddth')
  FROM DUAL

Result:

01st

When testing, using 'd' for the format didn't return expected results because the value is interpreted as a Julian date. Either substring the output to remove the leading zero, or provide a full date string (doesn't matter to the TO_CHAR because it's only interested in the day of the month):

SELECT TO_CHAR(TO_DATE('1900-01-01', 'YYYY-MM-dd'), 'dth')
  FROM DUAL

Because calendar days end at 31, use the year value instead to handle numbers greater than 31:

SELECT TO_CHAR(TO_DATE('32-01-01', 'YYYY-MM-dd'), 'yyth')
  FROM DUAL

Result:

32nd

Maybe I'm oversimplifying, but it seems like the following should work just fine (for integers) and is a lot more readable than converting to a date and back:

select case 
       when initial_extent is null then null
       when substr(initial_extent,-2,1) = '1' 
            then initial_extent || 'th'
       else case substr(initial_extent,-1,1)
            when '1' then initial_extent || 'st'
            when '2' then initial_extent || 'nd'
            when '3' then initial_extent || 'rd'
            else initial_extent || 'th'
            end
       end as formatted_number
from user_tables
select  substr( to_char( to_date( abs( decode( mod( l_value, 10 ), 0, 4, mod( l_value , 10 )  ) ), 'YYYY' ), 'YTH' ), 2 ) as value
from    dual

Replace l_value with appropriate, hmmm, value. Should cover any numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM