73

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Olga
  • 1,516
  • 5
  • 17
  • 23
  • That's usually referred to a [Scientific Notation](http://en.wikipedia.org/wiki/Scientific_notation) (sometimes as Scientific E Notation, but whatever...) – Damien_The_Unbeliever Jun 08 '12 at 06:34

9 Answers9

101

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"
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • 8
    Mine not working. `Number("1.7976931348623157e308")` – The_ehT Sep 13 '15 at 19:34
  • 1
    @The_ehT It works for me. `typeof Number("1.7976931348623157e308")` returns "Number" for me when I run that exact code in the console. running it in console without the `typeof` returns the number "1.7976931348623157e+308". – Joseph Marikle Sep 14 '15 at 13:18
  • 2
    @JosephMarikle but I want my number in standard notation not in scientific. – The_ehT Sep 14 '15 at 15:19
  • @The_ehT Ah! that makes sense. This question was on how to convert it to a "javascript number format" presumably to allow for working with it and other numbers, performing math against the numeric value. You want to convert yours to the extended format, which you would need a string for. Try this answer: http://stackoverflow.com/questions/16139452/how-to-convert-big-negative-scientific-notation-number-into-decimal-notation-str?lq=1 – Joseph Marikle Sep 14 '15 at 16:07
  • Thanks for the reply. I can convert that way but some digits gets lost if I do like that. For eg. I have a recursive function where last answer coming like 4.12345678e10, if I convert this to standard notation it would result like this 41234567800 where last two digits 00 are not actually 00. So it would be better if there is a way to prevent conversion to scientific notation or any other hack. – The_ehT Sep 14 '15 at 16:36
  • This is pretty dependent on the source of the data. Is it a javascript source? Generally, the scientific notation should only ever come into play when you're trying to format it for display. For instance, if you have a number that results in 4.12345678e10 but is stored as 4.1234567873, it should remain the second option in your variable until you try to convert it to a string to be passed to a server or stored in a DB or whatever else reason. Where in your application does it get passed as the scientific notation? – Joseph Marikle Sep 14 '15 at 17:36
  • May be running into the issue of javascript's max integer value: http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin – Joseph Marikle Sep 14 '15 at 17:41
  • Not work for this number `Number('2.801831040211423e+28')` – Mr Lou Feb 18 '18 at 14:19
  • @janwen Once again, `typeof Number('2.801831040211423e+28')` will indicate that it is in fact converting it to a number. If you're wanting to convert it to something more suitable for presentation, you might consider converting it to a formatted string. [This was linked above and might be useful to you.](https://stackoverflow.com/questions/16139452/how-to-convert-big-negative-scientific-notation-number-into-decimal-notation-str?lq=1) – Joseph Marikle Feb 19 '18 at 14:33
  • Does'nt work for Number(1234567890*999999999999999).toString() – RK_15 Mar 27 '19 at 07:15
  • @RK_15 Please re-read the question and answer. That code snippet is unrelated to my response. It looks like you're trying to convert a large number to a string, but this question and answer is the opposite. OP was trying to convert a scientific notation string to a number. – Joseph Marikle Mar 27 '19 at 13:40
  • how about 3.8e-7, i get the same output number 3.8e-7 – sasha romanov Aug 25 '19 at 03:51
  • @sasharomanov Please see my edit. Getting back `3.8e-7` is expected behavior. The person originally asking the question was *wanting* a number. You can't easily add 0.5 to the ***string*** "0.00000038". Therefore, my assumption is that you might actually be needing to convert your scientific notation to a string for presentation purposes. For that you can try checking out [this question](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) – Joseph Marikle Aug 26 '19 at 13:26
  • ```parseInt(Number('1e+20') ) 100000000000000000000 parseInt(Number('1e+21') ) 1 Math.floor(Number('1e+20') ) 100000000000000000000 Math.floor(Number('1e+21') ) 1e+21``` Works for my use case, trying to get ints from a very large string in scientific notation – Justin May 30 '20 at 23:09
  • `.toLocaleString('fullwide', {useGrouping:false})` saved me :) Thank you. – Duy Hưng Androgyne Tenor Aug 04 '22 at 08:18
13

I had a value like this 3.53048874968162e-09 and using Number.toFixed(20) worked for me:

value = new Number('3.53048874968162e-09')
//[Number: 3.53048874968162e-9]
value.toFixed(20)
//'0.00000000353048874968'
Matt Riedemann
  • 131
  • 1
  • 2
  • 1
    Please consider adding an explanation *why* it worked and a reference, especially when adding one to an old question (such answers go to the review queue). Note that the question is not about formatting strings representing numbers but about *converting* to a number format (although the confusion is understandable given how the q. is formulated). – Oleg Valter is with Ukraine May 20 '20 at 02:27
  • Also, you should not create new Number objects `new Number()` just to perform type conversion, use the `Number()` directly (will return a primitive type) – Oleg Valter is with Ukraine May 20 '20 at 02:34
11

Try something like this

Demo

Number("4.874915326E7").toPrecision()
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 4
    `.toPrecision()` isn't needed here, and adds scientific notation if the precision is lower than the supplied string. – Cees Timmerman May 08 '16 at 21:23
  • 1
    Number("2.2356434336665664e+51").toPrecision() this is not working .. please help me to rectify this issue. – BALAJI R Aug 08 '19 at 11:42
10

You can also use + sign in front of your string to get a number.

+"4.874915326E7" // == 48749153.26
Yaroslav Melnichuk
  • 820
  • 1
  • 11
  • 15
2

Preamble

While other answers are sufficient and correct, to be able to correctly parse numbers from strings, it is useful to understand how type coercion (conversion in your case) works at least at high level.

Coercion rules

There are rules that define how conversion is performed when you invoke utilities like parseInt, parseFloat, Number constructor or + unary operator:

parseInt(<value>, [radix]) function:

  • ignores leading whitespaces (" 24" -> 24)
  • empty strings return NaN
  • first non-numeric char finishes parsing (" 42answer" -> 42)
  • under above rule, decimal places finish parsing as well

The third rule is exactly why exponent part (ExponentPart consists of ExponentIndicator and SignedInteger as defined in standard) is ignored - as soon as the e char is encountered, parsing stops and the function returns the number parsed so far. In fact, it stops earlier - when the decimal point is first encountered (see the last rule).

parseFloat() is identical to parseInt, except:

  • it parses first decimal point
  • ignores leading 0 (thus hexadecimal can't be parsed)

As a rule of thumb, you should use parseInt when converting to an "integer" and parseFloat to "float" (note that they are actually the same type).

Number() constructor and unary +:

  • For boolean -> true to 1, false to 0

  • For null -> 0 (because null is falsy)

  • For undefined -> NaN

  • For numbers: pass-through

  • For strings:

    • only numeric [0-9] chars, starts with numeric or + or - -> number (integer)
    • same, but contains floating-point -> number (floating-point)
    • contains hexadecimal -> number (integer)
    • empty string -> 0
    • all other cases -> NaN
  • For objects, their valueOf() method is called. If result is NaN, then toString() method is called. Under the hood, the object is converted to primitive and that primitive is converted to number.

  • For symbols and BigInts -> TypeError is thrown

Note on number format

As the question still attracts answers and comments that are concerned with formatting (as validly stated by the accepted answer), it should be stated that:

As applied to programming, there is a strict meaning of "number format":
representation of the numeric value

"conversion" also has a strict meaning as type conversion (see standard)

ECMAScript implements double-precision 64-bit format and that's the only "format" it has. The question asks about converting a String to number format, therefore answers are expected to provide info on:

How to convert String to Number given the value represents a number in e-notation

References

  1. ToNumber abstract operation in ECMAScript standard
  2. One of the best reads I had on this topic and many others: Matt Frisbie's "Professional Javascript for Web Developers".
  3. Type coercion explained (blog post)
Community
  • 1
  • 1
1

For integers you can use BigInt. Not very precise for really big numbers, but works perfectly and I found it the most concise and easy to remember options:

BigInt(1e18).toString() => '1000000000000000000'
BigInt(1e36).toString() => '1000000000000000042420637374017961984'

BigInt(Math.round(4.874915326E7)).toString() => '48749153'
BitOfUniverse
  • 5,903
  • 1
  • 34
  • 38
0

Using MathJs library worked best for me, tried a lot of these answers and none of them worked properly under certain circumstances. This worked perfectly. More at https://mathjs.org/

Solution, add MathJS and then call it like this:

<script src="https://cdn.jsdelivr.net/npm/mathjs@8.0.1/lib/browser/math.js"  crossorigin="anonymous"></script>
    
    function toPlainString(num) {
        return math.format(num,  {notation: 'fixed'});
    }
otterslide
  • 550
  • 6
  • 14
  • 2
    Honestly I'm not a huge fan of the idea of importing an entire library for a solution that can be achieved with one line of native code. This is how we write big, inefficient applications and should be considered bad practice. – dudewad Apr 20 '22 at 15:01
0

For me the easy/safest way is the following:

export function stringifyNumber(num: number) {
    const [integer, decimals] = num.toString().split(".");
    if (decimals) {
        return BigInt(integer).toString() + "." + BigInt(decimals).toString();
    }
    return BigInt(integer).toString();
}
0
function convertScientificToDecimal(number) {
  const decimalPlaces = -Math.floor(Math.log10(Math.abs(number)));
  return Number(number.toFixed(decimalPlaces));
}

const numberInScientificNotation = 3.5209577676952493e-10;
const decimalNumber = convertScientificToDecimal(numberInScientificNotation);

console.log(decimalNumber); // 0.0000000004
Serhii Zharkov
  • 496
  • 5
  • 22