Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/core/src/lib/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,13 @@ describe('Helpers Utils Namespace', () => {
precision: 10,
});
expect(result5).toBe('1.5');

// Large values should not lose precision through JS number conversion
const result6 = PushChain.utils.helpers.formatUnits(
'123456789012345678901234567890',
{ decimals: 18, precision: 6 }
);
expect(result6).toBe('123456789012.345678');
});

it('should handle edge cases with precision', () => {
Expand Down
18 changes: 13 additions & 5 deletions packages/core/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -538,12 +538,20 @@ export class Utils {
formatted = formatted + '.0';
}

// Apply precision if specified
// Apply precision if specified without converting through JS number,
// which would lose precision for large token values.
if (precision !== undefined) {
const num = parseFloat(formatted);
const factor = Math.pow(10, precision);
const truncated = Math.floor(num * factor) / factor;
return truncated.toString();
if (precision === 0) {
return formatted.split('.')[0];
}

const [integerPart, fractionalPart = ''] = formatted.split('.');
const truncatedFraction = fractionalPart.slice(0, precision);
if (!truncatedFraction) {
return integerPart;
}

return `${integerPart}.${truncatedFraction.replace(/0+$/, '')}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return zero instead of a dangling decimal

When the requested precision keeps only zero fractional digits, truncatedFraction is truthy before the trailing-zero trim, so this returns a dangling decimal point. For example, formatUnits('1', { decimals: 18, precision: 2 }) now returns "0." instead of the previous/expected "0", which breaks small values below the display precision.

Useful? React with 👍 / 👎.

}

return formatted;
Expand Down