Jel. Number

Utility Methods for manipulating JavaScript’s built-in Number class

Summary
Utility Methods for manipulating JavaScript’s built-in Number class
gets a string representation for a given number padded out with leading zeros to a given length
gets the English ordinal suffix for a given number (st, nd, rd, th)
formats a given number in a specified display format

Functions

leadingZero

leadingZero: function(number,
toLength)

gets a string representation for a given number padded out with leading zeros to a given length

Arguments

numberNumber, the number to append leading zeros to
toLengthinteger, optional, the total length of the final leading-zero-padded string.  If not specified, defaults to a length of 2

Examples

Jel.Number.leadingZero(1);        // 01
Jel.Number.leadingZero(1, 3); // 001
Jel.Number.leadingZero(10, 3); // 010
Jel.Number.leadingZero(1000, 3); // 1000

ordinalSuffix

ordinalSuffix: function(number)

gets the English ordinal suffix for a given number (st, nd, rd, th)

Arguments

numberNumber, the value to get the ordinal suffix for

Example

Jel.Number.ordinalSuffix(2);    // "st"
Jel.Number.ordinalSuffix(2); // "nd"
Jel.Number.ordinalSuffix(23); // "rd"
Jel.Number.ordinalSuffix(11); // "th"
Jel.Number.ordinalSuffix(14); // "th"

format

format: function(number,
format)

formats a given number in a specified display format

Arguments

numberNumber object, the number to format
formatstring, describes the format of the output string (see examples below)

Returns

stringthe formatted output string

Examples

Jel.Number.format(3129.95, "$#,###.##");  // $3,129.95
Jel.Number.format(3129.95, "$####.##"); // $3129.95
Jel.Number.format(329.95, "$#####.##"); // $329.95
Jel.Number.format(329, "$###"); // $329
Jel.Number.format(-329, "(###)"); // (329)
Jel.Number.format(-1234.95, "#,##0.##"); // -1,234.95
Jel.Number.format(0.01, "#.##"); // 01
Jel.Number.format(0.01, "#.###"); // 010
Jel.Number.format(0.01, "0.##"); // 0.01
Jel.Number.format(2, "00"); // 02
Jel.Number.format(2345, "00000"); // 02345
Jel.Number.format(45, "00000"); // 00045

Formatting Rules

# - substitutes for a number, but only if this position has a definite non-zero number here
0 - substitutes for a number always, using zero if this position has no definite non-zero number here
leadingZero: function(number,
toLength)
gets a string representation for a given number padded out with leading zeros to a given length
ordinalSuffix: function(number)
gets the English ordinal suffix for a given number (st, nd, rd, th)
format: function(number,
format)
formats a given number in a specified display format