简体   繁体   中英

Javascript Regular Expression to fix toPrecision(2) output

After going through num.toPrecision(2), you can get 123.45 rounding to a string 1.2e+2.

Best way I can see to fix this is:

num = 123.45;
num = num.toPrecision(2);

num = num.replace(/\.0e\+2/g, "00");
num = num.replace(/\.1e\+2/g, "10");
num = num.replace(/\.2e\+2/g, "20");
num = num.replace(/\.3e\+2/g, "30");
num = num.replace(/\.4e\+2/g, "40");
num = num.replace(/\.5e\+2/g, "50");
num = num.replace(/\.6e\+2/g, "60");
num = num.replace(/\.7e\+2/g, "70");
num = num.replace(/\.8e\+2/g, "80");
num = num.replace(/\.9e\+2/g, "90");

Output is 1.2e+2. I need 120 (or 970 instead of 9.7e+2, etc.).

Is there a javascript regex expression with a don't care condition feeding to output. Essentially do this in one instruction?

You can change the precision by dividing by a suitable exponent of 10, taking the floor, and remultiplying.

function change_precision(n, prec) {
  var num_digits = Math.floor(Math.log10(n));
  var new_digits = num_digits - prec;
  var multiplier = Math.pow(10, new_digits);
  return Math.floor(n / multiplier) * multiplier;
}

> change_precision(11111000, 2)
< 11000000

> change_precision(123.45, 4)
< 123.4

If you want to use regex, then you can change all regex for the following:

num = 123.45
num = num.toPrecision(2);    
num = num.replace(/\.(\d)e\+2/g, "$10") // "120"

If you prefer to keep num as number, then just transform the num again and then it will be fixed.

num = 123.45    
num = Number(num.toPrecision(2)) // 120

EDIT To fix the case for num.toPrecision(1)

num = 123.45
num = num.toPrecision(1);    
num = num.replace(/(?:\.)?(\d)e\+2/g, "$10") // "10"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM