为什么 Oracle 的 to_char() 函数要添加空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/240182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:35:38  来源:igfitidea点击:

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

oracle

提问by Igor Drincic

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

oracle的to_char()函数为什么要加空格?

select length('012'), 
       length(to_char('012')), 
       length(to_char('12', '000')) 
  from dual;

3, 3, 4

3, 3, 4

采纳答案by stjohnroe

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

您使用的格式掩码是固定宽度并允许使用减号

回答by Tony Andrews

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

额外的前导空格用于潜在的减号。要删除空间,您可以使用以下格式的 FM:

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)

顺便说一下,注意 to_char 需要一个 NUMBER 参数;to_char('012') 被隐式转换为 to_char(to_number('012')) = to_char(12)

回答by James Curran

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]  

回答by Jay Neumann

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

请注意,使用 'fm' 语法时,除非使用零指定,否则小数位后不会包含任何值。例如:

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

returns: '12,345.00'

返回:'12,345.00'

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

returns: '12,345.'

返回:'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).

如您所见,如果您期望小数点后有两个零(例如可能在费用报告中),这将是一个问题。