From 96405157f05582ae91fcdca2192836b5877a45d3 Mon Sep 17 00:00:00 2001 From: William O'Beirne Date: Thu, 27 Jul 2017 19:21:50 -0400 Subject: [PATCH] Fix number formatter (#99) * Fix initialState -> INITIAL_STATE rename * Fix number formatter for removing non-trailing zeroes, not handling zero decimals. Add tests. --- common/utils/formatters.js | 14 ++++++++++--- spec/utils/formatters.spec.js | 37 ++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/common/utils/formatters.js b/common/utils/formatters.js index d5d84e17..13a60557 100644 --- a/common/utils/formatters.js +++ b/common/utils/formatters.js @@ -12,10 +12,18 @@ export function combineAndUpper(...args: string[]) { // Use in place of angular number filter export function formatNumber(number: Big, digits: number = 3): string { let parts = number.toFixed(digits).split('.'); - parts[1] = parts[1].replace(/0+/, ''); - if (!parts[1]) { - parts.pop(); + + // Remove trailing zeroes on decimal (If there is a decimal) + if (parts[1]) { + parts[1] = parts[1].replace(/0+$/, ''); + + // If there's nothing left, remove decimal altogether + if (!parts[1]) { + parts.pop(); + } } + + // Commafy the whole numbers parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts.join('.'); diff --git a/spec/utils/formatters.spec.js b/spec/utils/formatters.spec.js index 31b02d46..0e1de394 100644 --- a/spec/utils/formatters.spec.js +++ b/spec/utils/formatters.spec.js @@ -1,4 +1,5 @@ -import { toFixedIfLarger } from '../../common/utils/formatters'; +import Big from 'big.js'; +import { toFixedIfLarger, formatNumber } from '../../common/utils/formatters'; describe('toFixedIfLarger', () => { it('should return same value if decimal isnt longer than default', () => { @@ -15,3 +16,37 @@ describe('toFixedIfLarger', () => { expect(toFixedIfLarger(numExample, 2)).toEqual(String(7.12)); }); }); + +describe('formatNumber', () => { + const pairs = [ + { + input: new Big('0.0127491'), + output: '0.013' + }, + { + input: new Big('21.87468421'), + output: '21.875' + }, + { + input: new Big(0), + output: '0' + }, + { + input: new Big('354.4728173'), + output: '354.4728', + digits: 4 + }, + { + input: new Big('100.48391'), + output: '100', + digits: 0 + } + ]; + + pairs.forEach(pair => { + const digits = pair.digits === undefined ? 'default' : pair.digits; + it(`should convert ${pair.input.toString()} to ${pair.output} when using ${digits} digits`, () => { + expect(formatNumber(pair.input, pair.digits)).toEqual(pair.output); + }); + }); +});