Fix parse number with empty string separators (#41792)
This commit is contained in:
commit
3d33482711
|
@ -0,0 +1,4 @@
|
|||
Significance: minor
|
||||
Type: fix
|
||||
|
||||
Fix parseNumber to allow for emptry string thousand & decimal separators.
|
|
@ -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 );
|
||||
}
|
||||
|
|
|
@ -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' );
|
||||
} );
|
||||
} );
|
||||
|
|
Loading…
Reference in New Issue