Skip to content

Library: formatNumber()

Eugene Lazutkin edited this page Jul 3, 2018 · 2 revisions

formatNumber() module is a function, which formats a number to the specified precision using decimal and millennial separators.

Usage

In a module-enabled environment (like Babel) it can be accessed like that:

import formatNumber from '@researchnow/reno/src/utils/formatNumber';

In global-based environments (like a browser) it is frequently mapped to Reno.utils.formatNumber.

formatNumber(number, precision=0, millennia=',', decimal='.')

The function takes the following arguments:

  • number is a number to be formatted. It will be rounded up to a specified precision using specified decimal and millennia separators.
  • precision is a number to round up. For example, 2 means "2 digits after a decimal point", -2 means "round off to hundreds", 0 means "integer". The default: 0.
  • millennia is a symbol to use as a separator for every three digits before a decimal point. The default: ','.
  • decimal is a symbol to use a separator between an integer part and a fractional part.

The return is a string, which contains a presentable number.

Examples

const x = formatNumber(Math.PI);
assert(x === '3.14');

const y = formatNumber(1234567.89012345, 3);
assert(y === '1,234,567.890');

const z = formatNumber(1234567.89012345, 2, ' ', ',');
assert(z === '1 234 567,89');

const w = formatNumber(1234567.89012345, -2);
assert(z === '1,234,600');

Clone this wiki locally