适用于:
Databricks SQL
Databricks Runtime 11.3 LTS 及更高版本
使用格式化 expr 返回转换为十进制的 fmt。
语法
to_number(expr, fmt)
fmt
{ ' [ MI | S ] [ L | $ ]
[ 0 | 9 | G | , ] [...]
[ . | D ]
[ 0 | 9 ] [...]
[ L | $ ] [ PR | MI | S ] ' }
参数
-
expr:表示数字的字符串表达式。expr可能包括前导或尾随空格。 -
fmt:一个字符串字面量,指定格式应为expr。
返回
DECIMAL(p, s),其中 p 是总位数(0 或 9),s 是小数点后的位数,如果没有,则为 0。
fmt 可以包含以下元素(不区分大小写):
0或9指定介于
0和9之间的所需数字。 小数点左边的0表示expr必须至少有同样多的位数。 前导9指示expr可能省略这些数字。expr不得大于小数点左边允许的位数。小数点右边的数字表示
expr在fmt指定的小数点右边可能具有的最大位数。.或D指定小数点的位置。
expr不需要包含小数点。,或G指定
,分组(千位)分隔符的位置。 每个分组分隔符的左右两边必须有一个0或9。expr必须匹配与数字大小相关的分组分隔符。L或$指定
$货币符号的位置。 此字符只能指定一次。S或MI指定
S可选的“+”或“-”符号的位置,MI仅允许“-”符号。 此指令只能指定一次。PR仅允许位于格式字符串的末尾;指定
expr表示带有尖括号 (<1>) 的负数。
如果 expr 包含除 0 到 9 或 fmt 中允许的字符之外的任何字符,则返回错误。
要返回 NULL 而不是表示 expr 无效的错误,请使用 try_to_number()。
示例
-- The format expects:
-- * an optional sign at the beginning,
-- * followed by a dollar sign,
-- * followed by a number between 3 and 6 digits long,
-- * thousands separators,
-- * up to two dight beyond the decimal point.
> SELECT to_number('-$12,345.67', 'S$999,099.99');
-12345.67
-- Plus is optional, and so are fractional digits.
> SELECT to_number('$345', 'S$999,099.99');
345.00
-- The format requires at least three digits.
> SELECT to_number('$45', 'S$999,099.99');
Error: INVALID_FORMAT.MISMATCH_INPUT
-- The format requires at least three digits.
> SELECT try_to_number('$45', 'S$999,099.99');
NULL
-- The format requires at least three digits
> SELECT to_number('$045', 'S$999,099.99');
45.00
-- Using brackets to denote negative values
> SELECT to_number('<1234>', '999999PR');
-1234