From a158605303875a01fb8e6bcf268623603fe12331 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 9 Apr 2022 10:41:39 +0200 Subject: [PATCH] Improve numbering format for small numbers --- src/shared/formatters/numberformat.ts | 13 ++++++++++--- tests/unit/formatters.spec.ts | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/shared/formatters/numberformat.ts b/src/shared/formatters/numberformat.ts index 9ec92479..3e3c0ee4 100644 --- a/src/shared/formatters/numberformat.ts +++ b/src/shared/formatters/numberformat.ts @@ -9,11 +9,18 @@ export function formatPercent(value: number, decimals = 3): string { /** * Format number to `decimals` without trailing zeros * @param value Number to format - * @param decimals number of decimals (Defaults to 8) + * @param decimals number of decimals (Defaults to 15) * @returns Formatted string */ -export function formatPrice(value: number, decimals = 8): string { - return !isUndefined(value) ? parseFloat(value.toFixed(decimals)).toString() : ''; +export function formatPrice(value: number, decimals = 15): string { + // const format = new Intl.NumberFormat('', {maximumFractionDigits: decimals} + // return !isUndefined(value) ? parseFloat(value.toFixed(decimals)).toString() : ''; + return !isUndefined(value) + ? value.toLocaleString('fullwide', { + useGrouping: false, + maximumFractionDigits: decimals, + }) + : ''; } /** diff --git a/tests/unit/formatters.spec.ts b/tests/unit/formatters.spec.ts index ceb6e70c..4e08a2cb 100644 --- a/tests/unit/formatters.spec.ts +++ b/tests/unit/formatters.spec.ts @@ -1,4 +1,4 @@ -import { formatPercent, formatPriceCurrency } from '@/shared/formatters'; +import { formatPercent, formatPrice, formatPriceCurrency } from '@/shared/formatters'; describe('formatters.ts', () => { it('Format percent correctly', () => { @@ -9,5 +9,19 @@ describe('formatters.ts', () => { expect(formatPriceCurrency(5123.551123, 'USDT', 3)).toEqual('5123.551 USDT'); expect(formatPriceCurrency(5123.551123, 'USDT')).toEqual('5123.551 USDT'); expect(formatPriceCurrency(5123.551123, 'USDT', 5)).toEqual('5123.55112 USDT'); + expect(formatPriceCurrency(5123.5511230000000001, 'USDT', 5)).toEqual('5123.55112 USDT'); + expect(formatPriceCurrency(0.00001, 'BTC', 5)).toEqual('0.00001 BTC'); + }); + + it('Format price correctly', () => { + expect(formatPrice(5123.5123512)).toEqual('5123.5123512'); + expect(formatPrice(5123.5123512, 8)).toEqual('5123.5123512'); + expect(formatPrice(5123.5123512, 3)).toEqual('5123.512'); + expect(formatPrice(5123.51200000000000001, 8)).toEqual('5123.512'); + expect(formatPrice(0.001, 3)).toEqual('0.001'); + expect(formatPrice(0.0019, 3)).toEqual('0.002'); + expect(formatPrice(2.701e-9, 3)).toEqual('0'); + expect(formatPrice(2.701e-9, 8)).toEqual('0'); + expect(formatPrice(2.701e-9, 11)).toEqual('0.0000000027'); }); });