Why is Oracle's to_char() function adding spaces?

后端 未结 4 527
[愿得一人]
[愿得一人] 2021-02-03 17:25

Why is Oracle\'s to_char() function adding spaces?

select length(\'012\'), 
       length(to_char(\'012\')), 
       length(to_char(\'12\', \'000\')         


        
相关标签:
4条回答
  • 2021-02-03 17:27

    The extra leading space is for the potential minus sign. To remove the space you can use FM in the format:

    SQL> select to_char(12,'FM000') from dual;
    
    TO_C
    ----
    012
    

    By the way, note that to_char takes a NUMBER argument; to_char('012') is implicitly converted to to_char(to_number('012')) = to_char(12)

    0 讨论(0)
  • 2021-02-03 17:32

    Be aware when using the 'fm' syntax it will not include any values after the decimal place unless specified using zeros. For example:

    SELECT TO_CHAR(12345, 'fm99,999.00') FROM dual                               
    

    returns: '12,345.00'

    SELECT TO_CHAR(12345, 'fm99,999.99') FROM dual                            
    

    returns: '12,345.'

    As you can see this would be an issue if you are expecting two zeros after the decimals place (maybe in fee reports for example).

    0 讨论(0)
  • 2021-02-03 17:41

    The format mask that you are using is fixed width and allows for a minus sign

    0 讨论(0)
  • 2021-02-03 17:45

    To make the answers given more clear:

    select '['||to_char(12, '000')||']', 
           '['||to_char(-12, '000')||']', 
           '['||to_char(12,'FM000')||']' 
    from dual
    
    
    [ 012]                      [-012]                       [012]  
    
    0 讨论(0)
提交回复
热议问题