Skip to content

Instantly share code, notes, and snippets.

@alanrsoares
Last active August 2, 2016 05:41
Show Gist options
  • Save alanrsoares/e1961f0e9b5f5fc5a39c7cdd4de8375e to your computer and use it in GitHub Desktop.
Save alanrsoares/e1961f0e9b5f5fc5a39c7cdd4de8375e to your computer and use it in GitHub Desktop.
Agnostic, extensible and composable set of functions for formatting numbers to currency
// :: delimitGroups = (number, string) => string => string
const delimitGroups = (groupSize, delimiter) => s =>
s.split('')
.reduceRight((acc, x, i) =>
`${x}${(s.length - 1 - i) % groupSize ? '' : delimiter}${acc}`)
// :: format = number => object => string
export const format = options => n =>
(([left, right]) =>
`${options.symbol}${
delimitGroups(options.groupSize, options.groupSeparator)(left)
}${options.decimalSeparator}${right}`
)(n.toFixed(options.decimals).split('.'))
// :: formatWithOptions = object => (number, object) => string
export const formatWithOptions = options => (n, overrides = {}) =>
format({
...options,
...overrides
})(n)
// USAGE
// configs
const currencyLocale = {
NZD: {
symbol: '$',
groupSize: 3,
groupSeparator: ',',
decimalSeparator: '.',
decimals: 2
},
BRL: {
symbol: 'R$',
groupSize: 3,
groupSeparator: '.',
decimalSeparator: ',',
decimals: 2
}
}
// high level localized wrappers
const formatNZD = formatCurrencyWithOptions(currencyLocale.NZD)
const formatBRL = formatCurrencyWithOptions(currencyLocale.BRL)
console.log(
formatNZD(2.32), // $2.32
formatNZD(11231232.324567, { decimals: 4, symbol: '' }), // 11,231,232.3246
formatBRL(32135.35267) // R$32.135,35
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment