Skip to content

ES Module for parsing and formatting mass units.

License

Notifications You must be signed in to change notification settings

TylerVigario/Mass.js

Repository files navigation

Mass.js

Node CI Coverage Status npm

ES Module for parsing and formatting mass units.

Demo | Demo Source

Install

npm install mass.js

Usage

import Mass from 'mass.js';

let value = Mass.parse('5 lbs 8 oz');  // Parse string for mass
value += 5.5;                          // Add 5.5 pounds
Mass.format(value);                    // Format total: "11 lb"
Mass.format(value, { written: true }); // Written format: "eleven pounds"

Units

Default system for units of mass is U.S. customary but can be changed by requiring an alternative entry point (US, UK, or SI).

import Mass from 'mass.js/entry/US'; // U.S. customary (default)
import Mass from 'mass.js/entry/UK'; // Imperial
import Mass from 'mass.js/entry/SI'; // International System of Units (unfinished)

Methods

.parse(text)

Parse string for mass.

text: string The string to parse.

Returns mass value as number, or if invalid text or negative values, false.


.format(value, options = {})

Format number as string.

value: number The number to format (must be positive).

options: Object The formatting options.

  • unit: (number|string) Base unit value or string for lookup (default: 1).

  • written: (Object|string|boolean) n2words options or language identifier (as string), otherwise boolean (default: false).

Returns value formatted as string, or if unit lookup fails, undefined.

Examples:

Mass.format(11);

Mass.format(176, {
    unit: 'oz',
    written: true
});

.parseSet(value, signifier)

Parse value with value signifier.

value: number The number to format (must be positive).


.lookup(signifier)

Lookup string signifier.

signifier: string The string to lookup.

Returns matching unit Object if found, otherwise undefined.