2019-01-17 00:32:12 +00:00
|
|
|
/** @format */
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2019-01-17 14:08:59 +00:00
|
|
|
import { get, isFinite } from 'lodash';
|
2019-01-17 00:32:12 +00:00
|
|
|
const number_format = require( 'locutus/php/strings/number_format' );
|
2019-01-17 14:08:59 +00:00
|
|
|
import { formatCurrency } from '@woocommerce/currency';
|
2019-01-17 00:32:12 +00:00
|
|
|
|
2018-08-08 23:52:21 +00:00
|
|
|
/**
|
|
|
|
* Formats a number using site's current locale
|
|
|
|
*
|
2019-01-17 23:25:44 +00:00
|
|
|
* @see http://locutus.io/php/strings/number_format/
|
2019-01-17 00:32:12 +00:00
|
|
|
* @param {Number|String} number number to format
|
2019-01-17 01:40:45 +00:00
|
|
|
* @param {int|null} [precision=null] optional decimal precision
|
2019-01-17 00:32:12 +00:00
|
|
|
* @returns {?String} A formatted string.
|
2018-08-08 23:52:21 +00:00
|
|
|
*/
|
2019-01-17 01:40:45 +00:00
|
|
|
export function numberFormat( number, precision = null ) {
|
2018-08-08 23:52:21 +00:00
|
|
|
if ( 'number' !== typeof number ) {
|
|
|
|
number = parseFloat( number );
|
|
|
|
}
|
2019-01-17 00:32:12 +00:00
|
|
|
|
2018-08-08 23:52:21 +00:00
|
|
|
if ( isNaN( number ) ) {
|
|
|
|
return '';
|
|
|
|
}
|
2019-01-17 00:32:12 +00:00
|
|
|
|
|
|
|
const decimalSeparator = get( wcSettings, [ 'currency', 'decimal_separator' ], '.' );
|
|
|
|
const thousandSeparator = get( wcSettings, [ 'currency', 'thousand_separator' ], ',' );
|
2019-01-17 23:25:44 +00:00
|
|
|
precision = parseInt( precision );
|
2019-01-17 00:32:12 +00:00
|
|
|
|
2019-01-17 23:25:44 +00:00
|
|
|
if ( isNaN( precision ) ) {
|
|
|
|
const [ , decimals ] = number.toString().split( '.' );
|
|
|
|
precision = decimals ? decimals.length : 0;
|
2019-01-17 01:40:45 +00:00
|
|
|
}
|
|
|
|
|
2019-01-17 00:32:12 +00:00
|
|
|
return number_format( number, precision, decimalSeparator, thousandSeparator );
|
2018-08-08 23:52:21 +00:00
|
|
|
}
|
2019-01-17 14:08:59 +00:00
|
|
|
|
|
|
|
export function formatValue( type, value ) {
|
|
|
|
if ( ! isFinite( value ) ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch ( type ) {
|
|
|
|
case 'average':
|
|
|
|
return Math.round( value );
|
|
|
|
case 'currency':
|
|
|
|
return formatCurrency( value );
|
|
|
|
case 'number':
|
|
|
|
return numberFormat( value );
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function calculateDelta( primaryValue, secondaryValue ) {
|
|
|
|
if ( ! isFinite( primaryValue ) || ! isFinite( secondaryValue ) ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ( secondaryValue === 0 ) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Math.round( ( primaryValue - secondaryValue ) / secondaryValue * 100 );
|
|
|
|
}
|