I decided to talk in detail about @Novellizator's answer to meet my needs. I wanted a flexible function to handle most of my formatting needs without external libraries.
Characteristics
- Ability to use order suffixes (k, M, etc.)
- Ability to specify your own list of order suffixes to use
- Ability to limit the minimum and maximum order
- Decimal number control
- Automatic comma separation
- Optional percentage or dollar formatting
- Control over what to return in case of non-numeric input
- Works on negative and infinite numbers
Examples
let x = 1234567.8; formatNumber(x); // '1,234,568' formatNumber(x, {useOrderSuffix: true}); // '1M' formatNumber(x, {useOrderSuffix: true, decimals: 3, maxOrder: 1}); // '1,234.568k' formatNumber(x, {decimals: 2, style: '$'}); // '$1,234,567.80' x = 10.615; formatNumber(x, {style: '%'}); // '1,062%' formatNumber(x, {useOrderSuffix: true, decimals: 1, style: '%'}); // '1.1k%' formatNumber(x, {useOrderSuffix: true, decimals: 5, style: '%', minOrder: 2}); // '0.00106M%' formatNumber(-Infinity); // '-∞' formatNumber(NaN); // '' formatNumber(NaN, {valueIfNaN: NaN}); // NaN
function
function formatNumber(number, { decimals = 0, valueIfNaN = '', style = '', useOrderSuffix = false, orderSuffixes = ['', 'k', 'M', 'B', 'T'], minOrder = 0, maxOrder = Infinity } = {}) { let x = parseFloat(number); if (isNaN(x)) return valueIfNaN; if (style === '%') x *= 100.0; let order; if (!isFinite(x) || !useOrderSuffix) order = 0; else if (minOrder === maxOrder) order = minOrder; else { const unboundedOrder = Math.floor(Math.log10(Math.abs(x)) / 3); order = Math.max( 0, minOrder, Math.min(unboundedOrder, maxOrder, orderSuffixes.length - 1) ); } const orderSuffix = orderSuffixes[order]; if (order !== 0) x /= Math.pow(10, order * 3); return (style === '$' ? '$' : '') + x.toLocaleString( 'en-US', { style: 'decimal', minimumFractionDigits: decimals, maximumFractionDigits: decimals } ) + orderSuffix + (style === '%' ? '%' : ''); }
MarredCheese Jul 04 '19 at 20:48 2019-07-04 20:48
source share