to_number

Convert a string to a specified number format

Definition

number to_number(string|number $text, string $culture)

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

Parameters

string|number $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

{
  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(`1,2`, 'en-US'),
  h: to_number(`1,2`, 'en-DK'),
  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,     // JSON uses a decimal point rather than a comma
  "h": 1,     // JSON uses a decimal point rather than a comma
  "i": 1,
  "j": null,
  "k": null
}