I want to make a function that takes an entered value and converts it to scientific notation (N x 10^a)
I've tried many different things, but I can't seem to get it right.
Example:
I enter 200. The converter converts it to 2 x 10^2
I want to make a function that takes an entered value and converts it to scientific notation (N x 10^a)
I've tried many different things, but I can't seem to get it right.
Example:
I enter 200. The converter converts it to 2 x 10^2
You can do something like this:
fiddle: http://jsfiddle.net/Q8avJ/9/
If you want a base 10 format like this:
m x 10n
Then you can use a function like this:
Test it out: http://jsfiddle.net/u1hd4zm9/
Only odd thing is that the toFixed method (in Chrome at least) will not round exact halves up, but down. For instance if you run this code:
It will print '2.5' and not '2.6' like you expect. However if you run this code:
It will print 3. So be aware of that.
At some point I wanted to use the coefficient and the exponent as numbers.
If you want to do that, you can use
toExponential
function, split the string and convert the items of the array to numbers.In the following snippet I assign the numbers to the
numInSciNot
object and print them in the wanted format.If you don't want to use them as numbers you can just use
replace
:In this snippet I've used RegExp to replace
e
ore+
(in the case of positive exponent).If you want to specify the number of digits after the decimal point, you can use
toExponential(NumberOfDigits)
in the above examples.