Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the result of "toPrecision" without the scientific notation?

Tags:

javascript

Based on http://www.mredkj.com/javascript/nfbasic2.html, following code will result in 5.6e+2.

num = 555.55; result = num.toPrecision(2); // result will equal 5.6e+2 

How can I let the output of the result variable be displayed without scientific notation (i.e., e)?

like image 869
Ricky Avatar asked Jan 14 '11 08:01

Ricky


People also ask

How do you report a number in scientific notation?

The Scientific format displays a number in exponential notation, replacing part of the number with E+n, in which E (exponent) multiplies the preceding number by 10 to the nth power. For example, a 2-decimal scientific format displays 12345678901 as 1.23E+10, which is 1.23 times 10 to the 10th power.

What is the difference between toFixed and toPrecision?

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

What is toPrecision in js?

The toPrecision() method returns a string representing the Number object to the specified precision.


2 Answers

To get a float with reduced precision, you could use toPrecision() like you do, and then parse the scientific notation with parseFloat(), like so:

result = parseFloat(num.toPrecision(2)); 

If you do not wish to reduce precision, you could use toFixed() to get the number with a certain number of decimals.

like image 109
Sebastian Paaske Tørholm Avatar answered Sep 28 '22 12:09

Sebastian Paaske Tørholm


Number((555.55).toPrecision(2)) 

http://jsfiddle.net/K5GRb/

like image 44
Tolgahan Albayrak Avatar answered Sep 28 '22 12:09

Tolgahan Albayrak