diff --git a/.changeset/itchy-chefs-march.md b/.changeset/itchy-chefs-march.md new file mode 100644 index 00000000000..26369b0c982 --- /dev/null +++ b/.changeset/itchy-chefs-march.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/math": patch +--- + +fix: minPrecision overriding last valid digits diff --git a/packages/math/src/bn.test.ts b/packages/math/src/bn.test.ts index 75349b5a492..f5f0028ec0d 100644 --- a/packages/math/src/bn.test.ts +++ b/packages/math/src/bn.test.ts @@ -451,6 +451,13 @@ describe('Math - BN', () => { precision: 8, }) ).toEqual('1,001,000,000.20000'); + + expect( + bn('100100020000').format({ + minPrecision: 4, + precision: 8, + }) + ).toEqual('100.10002'); }); it('should parse to bn unit from decimal/inputs/string values', () => { diff --git a/packages/math/src/decimal.ts b/packages/math/src/decimal.ts index 844982d8eaf..bb89a8a1c21 100644 --- a/packages/math/src/decimal.ts +++ b/packages/math/src/decimal.ts @@ -11,9 +11,9 @@ export function toFixed(value?: string | number, options?: ToFixedConfig) { // strip traling zeros limited by minPrecision if (minPrecision < precision) { - const firstNonZero = decimals.match(/[1-9]/); - const firstNonZeroIndex = firstNonZero?.index == null ? -1 : firstNonZero.index; - const keepChars = Math.max(minPrecision, firstNonZeroIndex + 1); + const trimmedDecimal = decimals.match(/.*[1-9]{1}/); + const lastNonZeroIndex = trimmedDecimal?.[0].length || 0; + const keepChars = Math.max(minPrecision, lastNonZeroIndex); decimals = decimals.slice(0, keepChars); }