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?

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

Try parseFloat instead of parseInt.

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

1 Comment

This won't give you 5345345345353453453453535 but only the rounded value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.