Skip to content

Instantly share code, notes, and snippets.

@nhensh
Last active February 21, 2018 09:27
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 nhensh/24a40785d734f7ce7d28f502f39278af to your computer and use it in GitHub Desktop.
Save nhensh/24a40785d734f7ce7d28f502f39278af to your computer and use it in GitHub Desktop.
Currency Input Mask
const getDigitsFromValue = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''
const padDigits = digits => {
const desiredLength = 3
const actualLength = digits.length
if (actualLength >= desiredLength) {
return digits
}
const amountToAdd = desiredLength - actualLength
const padding = '0'.repeat(amountToAdd)
return padding + digits
}
const removeLeadingZeros = number => number.replace(/^0+([0-9]+)/, '$1')
const addDecimalToNumber = number => {
const centsStartingPosition = number.length - 2
const dollars = removeLeadingZeros(
number.substring(0, centsStartingPosition)
)
const cents = number.substring(centsStartingPosition)
return `${dollars}.${cents}`
}
export const toCurrency = value => {
const digits = getDigitsFromValue(value)
const digitsWithPadding = padDigits(digits)
return addDecimalToNumber(digitsWithPadding)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment