Skip to content

Instantly share code, notes, and snippets.

@mijorus
Created March 16, 2024 12:41
Show Gist options
  • Save mijorus/6b4e00836055aca8ae28f0e99e76cba2 to your computer and use it in GitHub Desktop.
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
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);
}
@mijorus
Copy link
Author

mijorus commented Mar 16, 2024

floatStr('0,23', '.') => '0.23'
floatStr(',34') => '0,34'
floatStr('2,2,3', '.') =>'2.23'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment