Last active
February 21, 2018 09:27
-
-
Save nhensh/24a40785d734f7ce7d28f502f39278af to your computer and use it in GitHub Desktop.
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