sabu
sabu

Reputation: 2057

Large number in javascript

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?

Upvotes: 0

Views: 220

Answers (3)

Curtis
Curtis

Reputation: 103358

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.

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382130

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).

Upvotes: 3

Felipe Miosso
Felipe Miosso

Reputation: 7339

Try parseFloat instead of parseInt.

<script type="text/javascript">
    var value = parseFloat(5345345345353453453453535);
    alert(value);
</script>

Upvotes: 0

Related Questions