mirror of
https://github.com/status-im/MyCrypto.git
synced 2025-01-10 19:16:10 +00:00
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:
parent
c32edf4a0b
commit
96405157f0
@ -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('.');
|
||||
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user