Fix number formatter (#99)

* Fix initialState -> INITIAL_STATE rename

* Fix number formatter for removing non-trailing zeroes, not handling zero decimals. Add tests.
This commit is contained in:
William O'Beirne 2017-07-27 19:21:50 -04:00 committed by Daniel Ternyak
parent c32edf4a0b
commit 96405157f0
2 changed files with 47 additions and 4 deletions

View File

@ -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('.');

View File

@ -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);
});
});
});