Created
April 5, 2023 17:44
-
-
Save leojaimesson/327f8a7f9a2784889ab646942422420d to your computer and use it in GitHub Desktop.
currency mask
This file contains hidden or 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 NUMBER_TO_DEFINE_DECIMAL_SEPARATOR_AND_CURRENCY = 1.1; | |
function getDecimalSeparatorByLocale(locale) { | |
return new Intl.NumberFormat(locale) | |
.format(NUMBER_TO_DEFINE_DECIMAL_SEPARATOR_AND_CURRENCY) | |
.replace(/\d/g, ""); | |
} | |
function getThousandSeparatorByDecimalSeparator(decimalSeparator) { | |
if (decimalSeparator === ".") { | |
return ","; | |
} | |
return "."; | |
} | |
export function normalizeInitialValueByPrecision( | |
currentValue = "0", | |
decimalPlaces = 0 | |
) { | |
if (decimalPlaces === 0) { | |
return currentValue; | |
} | |
if (!String(currentValue).split(/,|\./)[1]) { | |
return String(currentValue) + ".".padEnd(decimalPlaces + 1, "0"); | |
} | |
let newValue = String(currentValue); | |
while (newValue.split(/,|\./)[1].length < decimalPlaces) { | |
newValue += "0"; | |
} | |
return newValue; | |
} | |
export function applyMask( | |
currentValue = "", | |
precision = 0, | |
locale = "en", | |
enabledThousandSeparator = false | |
) { | |
const decimalSeparator = getDecimalSeparatorByLocale(locale); | |
const thousandSeparator = enabledThousandSeparator | |
? getThousandSeparatorByDecimalSeparator(decimalSeparator) | |
: ""; | |
// extract digits. if no digits, fill in a zero. | |
const digits = String(currentValue).match(/\d/g) || ["0"]; | |
// remove leading zeros | |
while (digits.length > 1 && digits[0] === "0") { | |
digits.shift(); | |
} | |
// zero-pad a input | |
while (digits.length <= precision) { | |
digits.unshift("0"); | |
} | |
if (enabledThousandSeparator) { | |
for (let x = digits.length - precision - 3; x > 0; x = x - 3) { | |
digits.splice(x, 0, thousandSeparator); | |
} | |
} | |
if (precision > 0) { | |
// add the decimal separator | |
digits.splice(digits.length - precision, 0, decimalSeparator); | |
} | |
const newValue = digits.join(""); | |
return { | |
value: newValue | |
.replace(RegExp(thousandSeparator, "g"), "") | |
.replace(",", "."), | |
maskedValue: newValue | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment