-
Notifications
You must be signed in to change notification settings - Fork 2k
/
index.js
80 lines (75 loc) · 2.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/** @format */
/**
* External dependencies
*/
import { numberFormat } from 'i18n-calypso';
/**
* Internal dependencies
*/
import { getCurrencyDefaults } from './currencies';
export { getCurrencyDefaults };
/**
* Formats money with a given currency code
* @param {Number} number number to format
* @param {String} code currency code e.g. 'USD'
* @param {Object} options options object
* @param {String} options.decimal decimal symbol e.g. ','
* @param {String} options.grouping thousands separator
* @param {Number} options.precision decimal digits
* @param {String} options.symbol currency symbol e.g. 'A$'
* @returns {?String} A formatted string.
*/
export default function formatCurrency( number, code, options = {} ) {
const currencyDefaults = getCurrencyDefaults( code );
if ( ! currencyDefaults || isNaN( number ) ) {
return null;
}
const { decimal, grouping, precision, symbol } = { ...currencyDefaults, ...options };
const sign = number < 0 ? '-' : '';
const value = numberFormat( Math.abs( number ), {
decimals: precision,
thousandsSep: grouping,
decPoint: decimal,
} );
return `${ sign }${ symbol }${ value }`;
}
/**
* Returns a formatted price object.
* @param {Number} number number to format
* @param {String} code currency code e.g. 'USD'
* @param {Object} options options object
* @param {String} options.decimal decimal symbol e.g. ','
* @param {String} options.grouping thousands separator
* @param {Number} options.precision decimal digits
* @param {String} options.symbol currency symbol e.g. 'A$'
* @returns {?String} A formatted string e.g. { symbol:'$', integer: '$99', fraction: '.99', sign: '-' }
*/
export function getCurrencyObject( number, code, options = {} ) {
const currencyDefaults = getCurrencyDefaults( code );
if ( ! currencyDefaults || isNaN( number ) ) {
return null;
}
const { decimal, grouping, precision, symbol } = { ...currencyDefaults, ...options };
const sign = number < 0 ? '-' : '';
const absNumber = Math.abs( number );
const rawInteger = Math.floor( absNumber );
const integer = numberFormat( rawInteger, {
decimals: 0,
thousandsSep: grouping,
decPoint: decimal,
} );
const fraction =
precision > 0
? numberFormat( absNumber - rawInteger, {
decimals: precision,
thousandsSep: grouping,
decPoint: decimal,
} ).slice( 1 )
: '';
return {
sign,
symbol,
integer,
fraction,
};
}