@insightlabs/number-formatter
v1.0.2
Published
Helper for formatting numbers as currency, fixed, or percentages. Also includes phone number and basic date formatting.
Downloads
6
Readme
@insightlabs/number-formatter
Helpers for formatting numbers as Money, Percentages, and Fixed.
Install
npm install @insightlabs/number-formatter --save
#or
yarn add @insightlabs/number-formatter
Usage
Import Default Instance (Recommended)
Importing the default instance of Formatter will use the browser's current locale, if it can be determined. Otherwise, defaults to "en-US".
import format from "@insightlabs/number-formatter";
Import Class and create Instance
Importing the class definition will allow you to set the locale manually.
import { Formatter } from "@insightlabs/number-formatter";
const format = new Formatter("en-US");
//or
const format = new Formatter(); //equivalent to default import instance
Format as Percent
const result = format.asPct(0.1236, 1);
// result == "12.4%"
Format as Money
const result = format.asMoney(12345.67, 2);
//result == "$12,345.67"
Format as Fixed
const result = format.asFixed(123456.789, 1);
//result == "123,456.8"
const year = format.asFixed(1984, 0, false); //no separator
//year = "1984";
Format as Phone Number
const result = format.asPhoneNumber(5128675309);
//result = "512-867-5309"
//or
const result = format.asPhoneNumber(5128675309, "", ".");
//result = "512.867.5309"
//or
const result = format.asPhoneNumber(nonNumberOrString, "N/A");
//result = "N/A"
Format as Date
const d = new Date();
const date = format.asDate(d);
//date = "6/14/2019"
const time = format.asTime(d);
//time = "1:22:55 PM"
const datetime = format.asDateTime(d);
//datetime = "6/14/2019 1:22:37 PM"