I am creating an online calculator using JavaScript.
I have this to work out a calculation:
eval(expression).toPrecision(10);
This produces the right output in almost all cases. E.g.
eval('456456+45646486*45646884').toPrecision(10)
// Output: "2.083619852e+15"
eval('1/0').toPrecision(10)
// Output: "Infinity"
However
eval('4*1').toPrecision(10)
// Output: "4.000000000"
How do I trim the trailing zeros but also keep nice outputs above?
To remove the trailing zeros from a number, pass the number to the parseFloat() function. The parseFloat function parses the provided value, returning a floating point number, which automatically removes any trailing zeros.
Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.
toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.
Divide by 1 after using toPrecision. Javascript will trail the zeros, and there's no regexes needed.
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