Fix parse number with empty string separators (#41792)

This commit is contained in:
Damián Suárez 2023-11-29 17:39:45 -03:00 committed by GitHub
commit 3d33482711
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 48 additions and 6 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: fix
Fix parseNumber to allow for emptry string thousand & decimal separators.

View File

@ -135,10 +135,19 @@ export function parseNumber(
const [ , decimals ] = value.split( decimalSeparator );
parsedPrecision = decimals ? decimals.length : 0;
}
let parsedValue = value;
if ( thousandSeparator ) {
parsedValue = parsedValue.replace(
new RegExp( `\\${ thousandSeparator }`, 'g' ),
''
);
}
if ( decimalSeparator ) {
parsedValue = parsedValue.replace(
new RegExp( `\\${ decimalSeparator }`, 'g' ),
'.'
);
}
return Number.parseFloat(
value
.replace( new RegExp( `\\${ thousandSeparator }`, 'g' ), '' )
.replace( new RegExp( `\\${ decimalSeparator }`, 'g' ), '.' )
).toFixed( parsedPrecision );
return Number.parseFloat( parsedValue ).toFixed( parsedPrecision );
}

View File

@ -6,7 +6,7 @@ import { partial } from 'lodash';
/**
* Internal dependencies
*/
import { numberFormat } from '../index';
import { numberFormat, parseNumber } from '../index';
const defaultNumberFormat = partial( numberFormat, {} );
@ -48,3 +48,32 @@ describe( 'numberFormat', () => {
expect( numberFormat( config, '12345.6789' ) ).toBe( '12.345,679' );
} );
} );
describe( 'parseNumber', () => {
it( 'should remove thousand seperator before parsing number', () => {
const config = {
decimalSeparator: ',',
thousandSeparator: '.',
precision: 3,
};
expect( parseNumber( config, '12.345,679' ) ).toBe( '12345.679' );
} );
it( 'supports empty string as the thousandSeperator', () => {
const config = {
decimalSeparator: ',',
thousandSeparator: '',
precision: 3,
};
expect( parseNumber( config, '12345,679' ) ).toBe( '12345.679' );
} );
it( 'supports empty string as the decimalSeperator', () => {
const config = {
decimalSeparator: '',
thousandSeparator: ',',
precision: 2,
};
expect( parseNumber( config, '1,2345,679' ) ).toBe( '12345679.00' );
} );
} );