Cldr.Number.Parser.parse
parse
, go back to Cldr.Number.Parser module for more information.
Specs
parse(String.t(), Keyword.t()) :: {:ok, integer() | float() | Decimal.t()} | {:error, {module(), String.t()}}
Parse a string in a locale-aware manner and return a number.
Arguments
string
is anyt:String
options
is a keyword list of options
Options
:number
is one of:integer
,:float
,:decimal
ornil
. The default isnil
meaning that the type auto-detected as either aninteger
or afloat
.:backend
is any module that includesuse Cldr
and is therefore a CLDR backend module. The default isCldr.default_backend/0
.:locale
is any locale returned byCldr.known_locale_names/1
or aCldr.LanguageTag.t
. The default isoptions[:backend].get_locale/1
.
Returns
A number of the requested or default type or
{:error, {exception, message}}
if no number could be determined
Notes
This function parses a string to return a number but in a locale-aware manner. It will normalise digits, grouping characters and decimal separators.
It will transliterate digits that are in the
number system of the specific locale. For example, if
the locale is th
(Thailand), then Thai digits are
transliterated to the Latin script before parsing.
Some number systems do not have decimal digits and in this case an error will be returned, rather than continue parsing and return misleading results.
It also caters for different forms of
the +
and -
symbols that appear in Unicode and
strips any _
characters that might be used for
formatting in a string.
It then parses the number using the Elixir standard library functions.
If the option :number
is used and the parsed number
cannot be coerced to this type without losing precision
then an error is returned.
Examples
iex> Cldr.Number.Parser.parse("+1.000,34", locale: "de")
{:ok, 1000.34}
iex> Cldr.Number.Parser.parse("-1_000_000.34")
{:ok, -1000000.34}
iex> Cldr.Number.Parser.parse("1.000", locale: "de", number: :integer)
{:ok, 1000}
iex> Cldr.Number.Parser.parse "١٢٣٤٥", locale: "ar"
{:ok, 12345}
# 1_000.34 cannot be coerced into an integer
# without precision loss so an error is returned.
iex> Cldr.Number.Parser.parse("+1.000,34", locale: "de", number: :integer)
{:error,
{Cldr.Number.ParseError,
"The string \"+1.000,34\" could not be parsed as a number"}}
iex> Cldr.Number.Parser.parse "一万二千三百四十五", locale: "ja-u-nu-jpan"
{:error,
{Cldr.UnknownNumberSystemError,
"The number system :jpan is not known or does not have digits"}}