I'm looking for a way to clean a number in Javascript, stripping all non-numeric characters unless it would break scientific notation. For example, I am looking for the following output...
123.45 => 123.451a23.45 => 123.451a23.4re5 => 123.45*(@#123.45jkd => 123.457.71234e+1 => 7.71234e+1I am more than happy to split on the . first and deal with the number as 2 different parts, if need be.
You can return any string that evaluates to a number,
and clean the ones that don't.
function cleanNumber(num){
var N= Number(num);
if(parseFloat(num)=== N) return num;
return num.replace(/\D+/g, '') || '0';
}
cleanNumber('7.71234e+1')
(String) 7.71234e+1
Or you can convert the strings to numbers and return a number-
function cleanNumber2(num){
var N= Number(num);
if(parseFloat(num)=== N) return N;
return Number(num.replace(/\D+/g, '')) || 0;
}
cleanNumber2('7.71234e+1');
(Number) 77.1234
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With