適用於:
Databricks SQL
Databricks Runtime 11.3 LTS 和更新版本
使用格式 expr 傳回 fmt 轉換成 DECIMAL。
語法
to_number(expr, fmt)
fmt
{ ' [ MI | S ] [ L | $ ]
[ 0 | 9 | G | , ] [...]
[ . | D ]
[ 0 | 9 ] [...]
[ L | $ ] [ PR | MI | S ] ' }
引數
-
expr:代表數位的 STRING 運算式。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