Skip to content

Instantly share code, notes, and snippets.

@ddikodroid
Created February 3, 2022 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddikodroid/4fd805ac0e4d94ea71c3fc04aeb1f0ad to your computer and use it in GitHub Desktop.
Save ddikodroid/4fd805ac0e4d94ea71c3fc04aeb1f0ad to your computer and use it in GitHub Desktop.
const currencyCode = 'Rp '
const currencyPosition = 'left'
const maxFractionDigits = 2
const decimalSeparator = ','
const thousandSeparator = '.'
function position(currencyPosition, value) {
return currencyPosition === 'left'
? `${currencyCode}${value}`
: `${value}${currencyCode}`
}
const convertToRupiah = (value) => {
let result
if (
value === 0 ||
value === null ||
value === undefined ||
value === '0' ||
typeof value === 'string'
) {
return position(currencyPosition, 0)
}
const currencyCheck = currencyCode.replace(/\s/g, '').toLowerCase()
if (currencyCheck === 'idr' || currencyCheck === 'rp') {
value = Math.ceil(value)
}
const valueSplit = String(value.toFixed(maxFractionDigits)).split(
`${thousandSeparator}`
)
const firstvalue = valueSplit[0]
const secondvalue = valueSplit[1]
const valueReal = String(firstvalue).replace(
/\B(?=(\d{3})+(?!\d))/g,
`${thousandSeparator}`
)
if (Number(secondvalue) > 0) {
result = position(
currencyPosition,
`${valueReal}${thousandSeparator}${secondvalue}`
)
} else {
result = position(currencyPosition, `${valueReal}`)
}
return result
}
export default convertToRupiah
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment