fix(localize): parseNumbers as heuristic if there is only 1 separator and 2 or less decimals e.g. 12.34 (#1976)

This commit is contained in:
gerjanvangeest 2023-05-17 12:07:00 +02:00 committed by GitHub
parent 9a845344fb
commit 88e6ca03ca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 6 deletions

View file

@ -0,0 +1,5 @@
---
'@lion/ui': patch
---
[localize] parseNumbers as heuristic if there is only 1 separator and 2 or less decimals e.g. 12.34

View file

@ -23,9 +23,15 @@ import { getDecimalSeparator } from './getDecimalSeparator.js';
function getParseMode(value, { mode = 'auto' } = {}) {
const separators = value.match(/[., ]/g);
if (!separators || (mode === 'auto' && separators.length === 1)) {
if (!separators) {
return 'withLocale';
}
if (mode === 'auto' && separators.length === 1) {
const decimalLength = value.split(`${separators}`)[1].length;
if (decimalLength >= 3) {
return 'withLocale';
}
}
if (separators.length === 1 || separators[0] !== separators[separators.length - 1]) {
return 'heuristic';
}

View file

@ -80,18 +80,32 @@ describe('parseNumber()', () => {
expect(parseNumber('1 234 56')).to.equal(123456);
});
it('uses locale to parse amount if there is only one separator e.g. 1.234', () => {
it('uses heuristic to parse amount if there is only one separator e.g. 12.34 and amount of decimals is 2 or smaller', () => {
localizeManager.locale = 'en-GB';
expect(parseNumber('12.3')).to.equal(12.3);
expect(parseNumber('12,3')).to.equal(12.3);
expect(parseNumber('12.34')).to.equal(12.34);
expect(parseNumber('12,34')).to.equal(1234);
expect(parseNumber('1.234')).to.equal(1.234);
expect(parseNumber('1,234')).to.equal(1234);
expect(parseNumber('12,34')).to.equal(12.34);
localizeManager.locale = 'nl-NL';
expect(parseNumber('12.34')).to.equal(1234);
expect(parseNumber('12.3')).to.equal(12.3);
expect(parseNumber('12,3')).to.equal(12.3);
expect(parseNumber('12.34')).to.equal(12.34);
expect(parseNumber('12,34')).to.equal(12.34);
});
it('uses locale to parse amount if there is only one separator e.g. 1.234 and amount of decimals is bigger then 2', () => {
localizeManager.locale = 'en-GB';
expect(parseNumber('1.234')).to.equal(1.234);
expect(parseNumber('1,234')).to.equal(1234);
expect(parseNumber('1.2345')).to.equal(1.2345);
expect(parseNumber('1,2345')).to.equal(12345);
localizeManager.locale = 'nl-NL';
expect(parseNumber('1.234')).to.equal(1234);
expect(parseNumber('1,234')).to.equal(1.234);
expect(parseNumber('1.2345')).to.equal(12345);
expect(parseNumber('1,2345')).to.equal(1.2345);
});
it('returns numbers only if it can not be interpreted e.g. 1.234.567', () => {