Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String containing Scientific Notation to correct Javascript number format

I have a String e.g: "4.874915326E7". What is the best way to convert it to a javascript number format? (int or float)? if I try parseInt(), the E at the end is ignored.

like image 400
Olga Avatar asked Jun 08 '12 06:06

Olga


2 Answers

Edit:

This answer seems to be generating some confusion. The original question was asking how to convert scientific notation in the form of a string to a number (so that it could be used for calculation). However, a significant number of people finding this answer seem to think it's about converting a number that is being represented by javascript as scientific notation to a more presentable format. If that is in fact your goal (presentation), then you should be converting the number to a string instead. Note that this means you will not be able to use it in calculations as easily.

Original Answer:

Pass it as a string to the Number function.

Number("4.874915326E7") // returns 48749153.26 Number("4E27") // returns 4e+27 

Converting a Number in Scientific Notation to a String:

This is best answered by another question, but from that question I personally like the solution that uses .toLocaleString(). Note that that particular solution doesn't work for negative numbers. For your convenience, here is an example:

(4e+27).toLocaleString('fullwide', {useGrouping:false}) // returns "4000000000000000000000000000" 
like image 80
Joseph Marikle Avatar answered Sep 21 '22 09:09

Joseph Marikle


Try something like this

Demo

Number("4.874915326E7").toPrecision() 
like image 27
Pranay Rana Avatar answered Sep 21 '22 09:09

Pranay Rana