From b67a2bbf4240acdc77237c4890027b3c30c40df7 Mon Sep 17 00:00:00 2001 From: Luiz Felipe Bolsoni Gomes Date: Tue, 1 Nov 2022 20:08:56 -0300 Subject: [PATCH 1/2] fix: minPrecision overriding last valid digits --- packages/math/src/bn.test.ts | 7 +++++++ packages/math/src/decimal.ts | 6 +++--- 2 files changed, 10 insertions(+), 3 deletions(-) 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); } From a53bc0608ca26eb84643824fb5f75face490e802 Mon Sep 17 00:00:00 2001 From: Luiz Felipe Bolsoni Gomes Date: Tue, 1 Nov 2022 20:09:36 -0300 Subject: [PATCH 2/2] chore: changeset --- .changeset/itchy-chefs-march.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/itchy-chefs-march.md 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