Globalite is a simple and lightweight library for internationalization in TypeScript/JavaScript.
It is inspired by Globalize but uses the built-in Intl object for
formatting and parsing dates, numbers, and currencies, instead of building its own formatting and parsing functions.
It also doesn't require the dependency of cldr-data or cldrjs.
It also adds support for parsing numbers in different international number systems to native JavaScript numbers,
and has number formatting and parsing specifier strings similar to that of .NET (for example E for scientific notation,
N for formatting with grouping separators, cUSD for currency using US dollars, etc.).
You can install Globalite via npm:
npm install @code-art-eg/globalite
or via yarn:
yarn add @code-art-eg/globalite
See documentation in docs for more details.
The number parser returns null if the input string is not a valid number instead of NaN returned by parseInt
, parseFloat and Globalize parser. This is because NaN can lead to bugs in your code if you don't check for it.
I have fallen into this trap many times and encountered bugs in my projects because I didn't check for NaN before
using the parsed number. So I think it's better to return null instead of NaN.
For example:
import { numberParser } from '@code-art-eg/globalite';
const parse = numberParser('en-US');
const number = parse('abc'); // returns null
doSomethingWithNumber(number); // TypeScript compiler error
function doSomethingWithNumber(num: number) {
// Do something with the number doesn't check if it's NaN
console.log(num);
}
In the above snippet, we don't check if the number is NaN in doSomethingWithNumber, but since parse returns null,
the TypeScript compiler will not allow calling doSomethingWithNumber with and passing a value that's possibly null.
To fix this, you can check if the number is null before calling doSomethingWithNumber:
const number = parse('abc'); // returns null
if (number !== null) {
doSomethingWithNumber(number);
}
I borrowed some logic from Globalize for the parsing functions. So a big thanks to the Globalize team for their work. I used their library for years, and it was a great help.