Rework numberFormat() to maintain decimal precision by default.
This commit is contained in:
parent
4bf7a79a84
commit
858ec82e8c
|
@ -10,10 +10,11 @@ const number_format = require( 'locutus/php/strings/number_format' );
|
|||
*
|
||||
* @see https://locutus.io/php/strings/number_format/
|
||||
* @param {Number|String} number number to format
|
||||
* @param {int|null} [precision=null] optional decimal precision
|
||||
* @returns {?String} A formatted string.
|
||||
*/
|
||||
|
||||
export function numberFormat( number ) {
|
||||
export function numberFormat( number, precision = null ) {
|
||||
if ( 'number' !== typeof number ) {
|
||||
number = parseFloat( number );
|
||||
}
|
||||
|
@ -22,9 +23,24 @@ export function numberFormat( number ) {
|
|||
return '';
|
||||
}
|
||||
|
||||
const precision = get( wcSettings, [ 'currency', 'precision' ], 2 );
|
||||
const decimalSeparator = get( wcSettings, [ 'currency', 'decimal_separator' ], '.' );
|
||||
const thousandSeparator = get( wcSettings, [ 'currency', 'thousand_separator' ], ',' );
|
||||
|
||||
if ( null === precision ) {
|
||||
const [ numberNoDecimals, decimals ] = number.toString().split( '.' );
|
||||
const formattedNumber = number_format(
|
||||
numberNoDecimals,
|
||||
0,
|
||||
decimalSeparator,
|
||||
thousandSeparator
|
||||
);
|
||||
|
||||
if ( decimals ) {
|
||||
return formattedNumber + decimalSeparator + decimals;
|
||||
}
|
||||
|
||||
return formattedNumber;
|
||||
}
|
||||
|
||||
return number_format( number, precision, decimalSeparator, thousandSeparator );
|
||||
}
|
||||
|
|
|
@ -5,8 +5,8 @@
|
|||
import { numberFormat } from '../index';
|
||||
|
||||
describe( 'numberFormat', () => {
|
||||
it( 'should default to precision=2 decimal=. thousands=,', () => {
|
||||
expect( numberFormat( 1000 ) ).toBe( '1,000.00' );
|
||||
it( 'should default to precision=null decimal=. thousands=,', () => {
|
||||
expect( numberFormat( 1000 ) ).toBe( '1,000' );
|
||||
} );
|
||||
|
||||
it( 'should return an empty string if no argument is passed', () => {
|
||||
|
@ -14,15 +14,18 @@ describe( 'numberFormat', () => {
|
|||
} );
|
||||
|
||||
it( 'should accept a string', () => {
|
||||
expect( numberFormat( '10000' ) ).toBe( '10,000.00' );
|
||||
expect( numberFormat( '10000' ) ).toBe( '10,000' );
|
||||
} );
|
||||
|
||||
it( 'maintains all decimals if no precision specified', () => {
|
||||
expect( numberFormat( '10000.123456' ) ).toBe( '10,000.123456' );
|
||||
} );
|
||||
|
||||
it( 'uses store currency settings, not locale', () => {
|
||||
global.wcSettings.siteLocale = 'en-US';
|
||||
global.wcSettings.currency.precision = 3;
|
||||
global.wcSettings.currency.decimal_separator = ',';
|
||||
global.wcSettings.currency.thousand_separator = '.';
|
||||
|
||||
expect( numberFormat( '12345.6789' ) ).toBe( '12.345,679' );
|
||||
expect( numberFormat( '12345.6789', 3 ) ).toBe( '12.345,679' );
|
||||
} );
|
||||
} );
|
||||
|
|
Loading…
Reference in New Issue