Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Trim .toPrecision() trailing zeros

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?

like image 694
Greg Avatar asked May 09 '13 21:05

Greg


People also ask

How do I remove trailing zeros in typescript?

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.

How do I round to 2 decimal places in JavaScript?

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.

What is difference between toFixed and toPrecision?

toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.


1 Answers

Divide by 1 after using toPrecision. Javascript will trail the zeros, and there's no regexes needed.

like image 156
Samantha Dove Avatar answered Sep 29 '22 19:09

Samantha Dove