Created
March 9, 2021 23:14
-
-
Save seanogdev/62c40e859e9bbcbf0cf47657f787a575 to your computer and use it in GitHub Desktop.
cent <-> formatted conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const currencyFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }) | |
/** | |
* | |
* @param {Intl.NumberFormat} currencyFormatter | |
* @returns Number | |
*/ | |
export const getConvertToCentValue = (currencyFormatter) => (number) => { | |
const parts = currencyFormatter.formatToParts(number); | |
const string = parts | |
.filter(({ type }) => ['integer', 'fraction'].includes(type)) | |
.reduce((string, { value }) => (string + value), '') | |
console.log('string:', string) | |
return parseInt(string) | |
}; | |
/** | |
* | |
* @param {Intl.NumberFormat} currencyFormatter | |
* @returns Number | |
*/ | |
export const getConvertFromCentValue = (currencyFormatter) => (value) => { | |
const resolvedOptions = currencyFormatter.resolvedOptions(); | |
const decimalPoints = resolvedOptions.maximumFractionDigits; | |
const zeroDecimalString = `.${'0'.repeat(decimalPoints)}`; | |
const currencyValue = value / parseInt(`1${'0'.repeat(decimalPoints)}`) | |
return `${currencyValue}`.replace(zeroDecimalString, '') | |
}; | |
// Currency-aware functions | |
const convertToCentValue = getConvertToCentValue(currencyFormatter); | |
const convertFromCentValue = getConvertFromCentValue(currencyFormatter); | |
console.log(convertToCentValue('7.50')) // 750 | |
console.log(convertFromCentValue('2090')) // 20.90 | |
console.log(convertFromCentValue('30')) // 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment