JavaScripTools Manual


Working with the NumberParser

The NumberParser is a class that can convert strings to numbers and numbers to strings using custom formatting options, like decimal and grouping separator, fixed amount of decimal digits, currency symbol and using parenthesis for negative numbers instead of a minus sign.

All those options can be set in 3 ways:

The availiable properties are the following, presented in the constructor parameters order:

Property Default value constant Description
decimalDigits JST_DEFAULT_DECIMAL_DIGITS The number of decimal digits (-1 Means no limit). When the number of digits is reduced, the standard round operation is used
decimalSeparator JST_DEFAULT_DECIMAL_SEPARATOR The decimal separator
groupSeparator JST_DEFAULT_GROUP_SEPARATOR The separator between integer groups (normally thousands)
useGrouping JST_DEFAULT_USE_GROUPING A flag indicating if the grouping separator be used
currencySymbol JST_DEFAULT_CURRENCY_SYMBOL A string representing the currency symbol
useCurrency JST_DEFAULT_USE_CURRENCY A flag indicating if the currencySymbol will be used
negativeParenthesis JST_DEFAULT_NEGATIVE_PARENTHESIS A flag indicating if, when the number is negative, surround it with parenthesis (true) use a minus sign (false)
groupSize JST_DEFAULT_GROUP_SIZE The number of integer digits to group. Normally 3 - thousands
spaceAfterCurrency JST_DEFAULT_SPACE_AFTER_CURRENCY A flag indicating if a space will be rendered after the currency symbol
currencyInside JST_DEFAULT_CURRENCY_INSIDE A flag indicating if, when the number is negative, the currency symbol will appear inside the minus sign or parenthesis (true) or outside (false)

When an invalid string is passed to the parse method the result is null.

This parser also has the round method, that takes a number and rounds it according to the parser decimalDigits (when it's -1, no rounding is performed).

Here are some examples:

var parser = new NumberParser();
parser.decimalDigits = 2;
parser.decimalSeparator = ",";
parser.groupSeparator = "."; 
parser.useGrouping = true; 

parser.parse("123,9") -> 123.9
parser.parse("123,917") -> 123.92 (round up)
parser.parse("9.876") -> 9876
parser.parse("ABC") -> null
parser.format(123456.781) -> "123.456,78"
parser.format(123456.789) -> "123.456,79" (round up)
parser.round(123456.789) -> 123456.79 (round up)

//Now we will use some attributes on the constructor
var parser2 = new NumberParser(2, ",", ".", true, "$", true);
parser2.format(-9876.5432) -> "$ -9.876,54"
parser2.negativeParenthesis = true;
parser2.format(-9876.5432) -> "$ (9.876,54)"
parser2.currencyInside = true;
parser2.format(-9876.5432) -> "($ 9.876,54)"

Introduction to Parsers
Table of Contents Next:
Working with the DateParser