共用方式為


to_number函式

適用於:核取記號為「是」 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 是數位總數 (09) ,而 s 是小數點後面的位數,如果沒有,則為 0。

fmt 可以包含下列元素(不區分大小寫):

  • 09

    指定一個位於09之間的預期數位。 0位於小數點左邊,表示expr必須至少擁有相同數量的數位。 前置 9 表示 expr 可能會省略這些數位。

    expr 不得大於小數點左側能容納的位數。

    小數點右邊的數位表示小數點右邊的位數 expr 可能比 fmt 指定數位多。

  • .D

    指定小數點的位置。

    expr 不需要包含小數點。

  • ,G

    指定群組 (千) 分隔符的位置 , 。 每個群組分隔符的左邊和右邊都必須有 09expr 必須符合與數位大小相關的群組分隔符。

  • L$

    指定貨幣符號的位置 $ 。 這個字元只能指定一次。

  • SMI

    指定選擇性 '+' 或 '-' 符號 S的位置,而 '-' 則只針對 MI指定 。 這個指令只能指定一次。

  • PR

    僅允許在格式字串結尾使用;expr 表示以包裹的角括弧(<1>)來指示負數。

如果 expr 包含除了09以外的任何字元,或在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