UNPKG

@js-data-tools/js-helpers

Version:

A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.

27 lines (26 loc) 887 B
const FACTORS = [1, 10, 100, 1000]; export function roundNumber(value, maxDecimalDigits = 2) { if (maxDecimalDigits < 0) { return value; } if (!maxDecimalDigits) { return Math.round(value); } const intPart = Math.trunc(value); const fraction = value - intPart; if (fraction === 0) { return intPart; } const factor = maxDecimalDigits < FACTORS.length ? FACTORS[maxDecimalDigits] : Math.pow(10, maxDecimalDigits); return intPart + Math.round(fraction * factor) / factor; } export function compactNumber(value, maxPower = 4, base = 1000) { let current = Math.abs(value); let power = 0; while (power < maxPower && current >= base) { current /= base; power++; } current = roundNumber(value < 0 ? -current : current, current < 100 ? 2 : current < base ? 1 : 0); return [current, power]; }