to_number

Convert a string to a specified number format

Definition

number to_number(string $text, string $culture)

Converts a string to a number, either floating-point or an integer, depending on the format. $culture defines the formatting of the string, namely the thousands separator and the decimal sign.

to_number supports converting decimal numbers of up to 8 digits in total. Longer decimals are rounded to the eighth digit and padded with zeros if the whole part is longer than 8 digits. The length limit doesn't apply to integers.

📘

For longer numbers, use to_large_decimal.

Parameters

string $text

A string to convert to a number. A number is returned without changes, while other input types will return null with no error.

string $culture

Define the thousands separator and the decimal sign according to a culture. The culture tag consists of a combination of a language and region tag, e.g., en-US.

Returns

number

If $text is a number, returns $text. If $text is a string, it's read as a number in accordance with the $culture specifier, and returned in its number representation. Other input types yield null output with no error.

Examples

{
  "numPoint": "1.2",
  "longNum": "1.23456789012"
}
{
  a: to_number('1.2', 'en-US'),
  b: to_number('1.2', 'en-DK'),
  c: to_number('1,2', 'en-US'),
  d: to_number('1,2', 'en-DK'),
  e: to_number(`1.2`, 'en-US'),
  f: to_number(`1.2`, 'en-DK'),
  g: to_number(numPoint, 'en-US'),
  h: to_number(longNum, 'en-US'),
  i: to_number(`1`, 'en-US'),
  j: to_number(`null`, 'en-US'),
  k: to_number([`0`], 'en-US')
}
{
  "a": 1.2,
  "b": 12,
  "c": 12,
  "d": 1.2,
  "e": 1.2,
  "f": 1.2,
  "g": 1.2,
  "h": 1.2345679,
  "i": 1,
  "j": null,
  "k": null
}