-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat-currency.ts
48 lines (41 loc) · 1.36 KB
/
format-currency.ts
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
import {FormatCurrencyParams, Money, FormattableNumber} from "../interfaces.js"
import {currencyLibrary as defaultCurrencyLibrary} from "../ecommerce/currency-library.js"
/**
* Round a number to the desired number of decimal places
*/
function precisionRound(value: number, precision: number): number {
const factor = Math.pow(10, precision)
return Math.round(value * factor) / factor
}
/**
* Display a number as a human-readable locale-abiding string
*/
function localize({value, precision, locale}: FormattableNumber): string {
return precisionRound(value, precision).toLocaleString(locale, {
maximumFractionDigits: precision,
minimumFractionDigits: precision
})
}
/**
* Format currency
* + express monetary value in human-readable format
* + displays large number groupings differently based on locale
* + defaults to 2 digits of precision
* + you can provide your own set of currency formatters
* + returns a string
*/
export function formatCurrency({
code,
value,
precision = 2,
locale = undefined,
currencyLibrary = defaultCurrencyLibrary,
}: FormatCurrencyParams): Money {
const currency = currencyLibrary[code]
if (!currency)
throw new Error(`unknown currency code "${code}"`)
const {symbol} = currency
const amount = localize({value, locale, precision})
const price = `${symbol}${amount} ${code}`
return {currency, amount, value, price}
}