Created
March 16, 2024 12:41
-
-
Save mijorus/6b4e00836055aca8ae28f0e99e76cba2 to your computer and use it in GitHub Desktop.
This functions is designed to be used in react inputs to collect float numbers. Given an input string and a decimal separator, it will return a new string with any non-numeric characters removed and only one decimal separator
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
function floatStr(str, outputDecimalSeparator = ',', possibleSeparators = [',', '.']) { | |
str = str.replace('.', outputDecimalSeparator); | |
str = str.replace(',', outputDecimalSeparator); | |
possibleSeparators.forEach(el => { | |
str = str.replace(el, outputDecimalSeparator); | |
}); | |
if (str.startsWith(outputDecimalSeparator)) { | |
str = '0' + str; | |
} | |
let [a, b] = str.split(outputDecimalSeparator, 2); | |
a = a.replace(/\D/g, ''); | |
if (typeof b === 'undefined') { | |
return a; | |
} | |
b = b.replace(/\D/g, ''); | |
return [a, b].join(outputDecimalSeparator); | |
} |
Author
mijorus
commented
Mar 16, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment