@gmjs/number-util v0.0.3
Number util
Number utility functions.
Install
npm install --save @gmjs/number-utilUsage
import { clamp } from '@gmjs/number-util';
const output = clamp(15, 10, 12);
console.log(output);
// 12API
clamp
Clamps the value number to the specified range.
const output = clamp(15, 10, 12);
console.log(output);
// 12parseFloatOrThrow
Parses a string to a float, or throws an error if the input is of invalid type or format.
The parsed string must match ^-?\d+(?:\.\d+)?$ regex to be considered valid.
const output = parseFloatOrThrow('15.123456');
console.log(output);
// 15.123456Here are some examples of invalid inputs:
parseFloatOrThrow('a'); // throws
parseFloatOrThrow('15.'); // throws
parseFloatOrThrow('+15'); // throws
parseFloatOrThrow('.12'); // throws
parseFloatOrThrow('5e2'); // throwsparseIntegerOrThrow
Parses a string to an integer, or throws an error if the input is of invalid type or format.
The parsed string must match ^-?\d+$ regex to be considered valid.
const output = parseIntegerOrThrow('15');
console.log(output);
// 15Here are some examples of invalid inputs:
parseIntegerOrThrow('a'); // throws
parseIntegerOrThrow('15.2'); // throws
parseIntegerOrThrow('+15'); // throwspadNonNegativeIntWithZeroes
Pads a non-negative integer with zeroes to the left, to the specified length.
const output = padNonNegativeIntWithZeroes(15, 5);
console.log(output);
// '00015'randomInteger
Returns a random integer in the [min, max> range. In other words, the min value is inclusive, and the max value is exclusive.
For example, randomInteger(10, 20) will return a random integer between 10 and 19 inclusive, it will never return 20.
const output = randomInteger(10, 20);
console.log(output);
// 15 (for example, but could be any integer between 10 and 19 inclusive)round
Rounds the value number to the specified number of decimal places.
const output = round(15.123456, 2);
console.log(output);
// 15.12If the precision parameter is omitted, the number is rounded to the nearest integer.
const output = round(15.123456);
console.log(output);
// 15