back to Overview

_.parseNumber()

Parses the given string as number using the given format.
Util module only.

Syntax

_.parseNumber(format, numberString)

Parameters

format
the format that describes the input number
numberString
the string-formatted number to parse
(return value)
the resulting number; undefined if parsing failed; or null if the string was empty and the number format is flagged as optional ('?' at the beginning)

Description

Parses the given string as number using the given format. parseNumber uses the same format as formatValue, but does not support choices. These are the allowed placeholders in the format:

CharacterDescription
#Optional digit before decimal separator.
0Required digit before decimal separator (0 if number is smaller).
_Optional digit after decimal separator.
9Required digit after decimal separator (0 if number is smaller).
.Either decimal separator or group separator, depending on position.
,Either decimal separator or group separator, depending on position.

The format string is mainly used to find out what the decimal separator is ('.' or ','). It defaults to '.'.

parseNumber will ignore any non-numeric characters at the beginning or end of the input string.

If you prefix the input string with a question mark ('?'), this means that the number is optional. If the input string is empty or consists solely of whitespace, parseNumber will return null.

If the input string is not valid and can not be parsed, parseNumber will return undefined.

Example

Parsing numbers in various formats.

_.parseNumber('00.99', '2.1');      // returns 2.1
_.parseNumber('00.99', '');          // returns undefined
_.parseNumber('?00.99', '2.1');    // optional number. Returns 2.1
_.parseNumber('?00.99', '');        // returns null
_.parseNumber('0.9', '=2.1 inch'); // returns 2.1 (non-numeric characters ignored)
_.parseNumber('0,9', '2,1');         // comma as decimal separator
_.parseNumber('0,9', '2.1');         // returns 21!! '.' is used as group separator
_.parseNumber('0.9', '20');         // returns 20 (number of digits ignored)
_.parseNumber('0.9', '147.789');  // returns 147.789  (number of digits ignored)

See also..

Comments

comments powered by Disqus

back to Overview

Functions