Skip to content

Commit

Permalink
chore: remove hardcoded small value formatting and configure with opt…
Browse files Browse the repository at this point in the history
…ions instead
  • Loading branch information
shan8851 committed Feb 24, 2025
1 parent a485c3c commit 7620b1e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
### Changed

- Update `NumberFormat.TOKEN_AMOUNT_SHORT` to round small numbers (between -0.01 and 0.01) to the nearest hundredth
- Add configurable options (`smallValueThreshold` and `smallValueFractionDigits`) to INumberFormat.
- Update `TOKEN_AMOUNT_SHORT` defaults in numberFormats.

## [1.0.68] - 2025-02-21

Expand Down
13 changes: 7 additions & 6 deletions src/core/utils/formatterUtils/formatterUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ class FormatterUtils {
withSign,
fallback = null,
displayFallback,
smallValueThreshold,
smallValueFractionDigits,
} = mergedOptions;

const parsedValue = typeof value === 'number' ? value : parseFloat(value ?? '');
Expand All @@ -65,15 +67,14 @@ class FormatterUtils {

let processedValue = isPercentage ? parsedValue * 100 : parsedValue;

// Special case TOKEN_AMOUNT_SHORT and the value is between -0.01 and 0.01
// We should round to the nearest hundredth meaning the only valid values are
// 0.00, 0.01, -0.01 and -0.00
if (format === NumberFormat.TOKEN_AMOUNT_SHORT) {
const applySmallValueFormatting = smallValueThreshold != null && smallValueFractionDigits != null;

if (applySmallValueFormatting) {
if (parsedValue === 0) {
return '0';
}
if (Math.abs(parsedValue) < 0.01) {
return parsedValue.toFixed(2);
if (Math.abs(parsedValue) < smallValueThreshold) {
return parsedValue.toFixed(smallValueFractionDigits);
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/core/utils/formatterUtils/formatterUtilsDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ export interface INumberFormat {
* the fallback when the value is NaN.
*/
displayFallback?: (value: number) => boolean;
/**
* Threshold value to consider a number as a small value and be formatted differently.
*/
smallValueThreshold?: number;
/**
* Number of fraction digits to use when formatting small values.
*/
smallValueFractionDigits?: number;
}

export enum NumberFormat {
Expand Down Expand Up @@ -81,6 +89,8 @@ export const numberFormats: Record<NumberFormat, INumberFormat> = {
[NumberFormat.TOKEN_AMOUNT_SHORT]: {
maxFractionDigits: 2,
useBaseSymbol: true,
smallValueThreshold: 0.01,
smallValueFractionDigits: 2,
},
[NumberFormat.TOKEN_AMOUNT_LONG]: {
maxFractionDigits: 18,
Expand Down

0 comments on commit 7620b1e

Please sign in to comment.