Created
February 3, 2022 07:12
-
-
Save ddikodroid/4fd805ac0e4d94ea71c3fc04aeb1f0ad to your computer and use it in GitHub Desktop.
This file contains 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 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