0

I am working on a calculator in javascript, where user can enter the values in textfield and operation will be performed. Now if user enters a very large value for example 5345345345353453453453535 it is converted to 5.345345345353453e+24

I am using parsrInt() to convert it to integers. and it gives me 5. which is wrong . Can anybody suggest how to solve it?

sabu
  • 1,969
  • 4
  • 18
  • 28
  • This might be useful: http://stackoverflow.com/questions/11124451/how-can-i-convert-numbers-into-scientific-notation – Schleis Feb 21 '13 at 15:17
  • 1
    possible duplicate of [How to deal with big numbers in javascript](http://stackoverflow.com/questions/4288821/how-to-deal-with-big-numbers-in-javascript) – JaredMcAteer Feb 21 '13 at 15:18

3 Answers3

3

Integers in javascript are, like every numbers, stored as IEEE754 double precision floats.

So you can only exactly store integers up to 2^51 (the size of the mantissa).

This means you'll have to design another format for dealing with big integers, or to use an existing library like BigInteger.js (Google will suggest a few other ones).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Taken from Mozilla documentation:

Parses a string argument and returns an integer of the specified radix or base.

Therefore parseInt() is taking your value as a string 5.345345345353453e+24

It is then ignoring any non-integer values and classing this as a decimal (5.345...) and then evaluating this to 5.


As @dystroy has pointed out, if you wish to carry out calculations with these large numbers you'll need to use a custom format, or use a pre-existing javascript library.

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
0

Try parseFloat instead of parseInt.

<script type="text/javascript">
    var value = parseFloat(5345345345353453453453535);
    alert(value);
</script>
Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55