Skip to content

Commit

Permalink
fix(CurrencyInput): allow to work with very small or large values (#3200
Browse files Browse the repository at this point in the history
)
  • Loading branch information
HelenaIsh committed Jul 17, 2023
1 parent 9795006 commit ffc234f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
25 changes: 20 additions & 5 deletions packages/react-ui/components/CurrencyInput/CurrencyHelper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ export class CurrencyHelper {
if (isNullable(value)) {
return '';
}

return CurrencyHelper.formatString(value.toString(), options);
return CurrencyHelper.formatString(this.toDecimalString(value), options);
}

public static parse(value: string): Nullable<number> {
Expand Down Expand Up @@ -202,11 +201,27 @@ export class CurrencyHelper {
}

public static destructString(value: string) {
const match = /^(-)?(\d*)?(\.)?(\d*)?$/.exec(value);
const match = /^(-)?(\d*)?(\.)?(\d*)?(e)?([-+]?\d+)?$/.exec(value);
if (!match) {
return null;
}
const [, sign = '', integer = '', delimiter = '', fraction = ''] = match;
return { sign, integer, delimiter, fraction };
const [, sign = '', integer = '', delimiter = '', fraction = '', , exponent = ''] = match;
return { sign, integer, delimiter, fraction, exponent };
}

private static toDecimalString = (number: number) => {
if (!number.toString().includes('e')) {
return number.toString();
}
const destructed = this.destructString(number.toExponential());
if (destructed === null) {
return '';
}
const { sign = '', integer, fraction, exponent } = destructed;
const intExponent = parseInt(exponent || '0');
if (intExponent > 0) {
return [sign, integer, fraction, '0'.repeat(intExponent - fraction.length)].join('');
}
return [sign, '0.', ' 0'.repeat(-intExponent - 1), integer, fraction].join('');
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ describe('CurrencyHelper', () => {
{ value: -0, expected: '0' },
{ value: -1, expected: '\u22121' },
{ value: -1234567, expected: '\u22121\u2009234\u2009567' },
{ value: 1e-7, expected: '0,0000001' },
{ value: -1e-7, expected: '\u22120,0000001' },
{ value: 1e22, expected: '10\u2009000\u2009000\u2009000\u2009000\u2009000\u2009000\u2009000' },
{ value: 1.425e-8, expected: '0,00000001425' },
{ value: 14.25e-8, expected: '0,0000001425' },
{ value: 1.425e22, expected: '14\u2009250\u2009000\u2009000\u2009000\u2009000\u2009000\u2009000' },
{ value: -1.425e22, expected: '\u221214\u2009250\u2009000\u2009000\u2009000\u2009000\u2009000\u2009000' },
{ value: 14.25e22, expected: '142\u2009500\u2009000\u2009000\u2009000\u2009000\u2009000\u2009000' },
{ value: 0.04e-10, expected: '0,000000000004' },
].forEach((x) => {
it(`format(${x.value}) === '${x.expected}'`, () => {
const actual = CurrencyHelper.format(x.value);
Expand Down

0 comments on commit ffc234f

Please sign in to comment.