Currency Input Mask
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 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