Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to strip all non numeric characters except scientific notation

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.45
  • 1a23.45 => 123.45
  • 1a23.4re5 => 123.45
  • *(@#123.45jkd => 123.45
  • 7.71234e+1 => 7.71234e+1

I am more than happy to split on the . first and deal with the number as 2 different parts, if need be.

like image 455
Brian David Berman Avatar asked Dec 04 '25 13:12

Brian David Berman


1 Answers

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

like image 176
kennebec Avatar answered Dec 07 '25 03:12

kennebec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!