Javascript parse int rounding issue [duplicate] - javascript

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
If I do the following:
parseInt(parseFloat(9.20)*100*1)/100 // returns 9.19
It returns 9.19 when I want it to return 9.20 what do I need to change to get it to return the correct value?
I have the same issue when I change it to:
parseInt(parseFloat(9.12)*100*1)/100 // returns 9.11
But any other value works fine:
parseInt(parseFloat(9.30)*100*1)/100 // returns 9.30 (correct)
UPDATE:
The solution was this:
(Math.round(9.20*100*1)/100).toFixed(2)

The problem is that 9.20*100 in Javascript returns 919.9999999999999, and not 920, because of floating point errors. When you do a parseInt() on that, it doesn't round to the nearest int, and instead truncates it to 919, which is why your final answer is wrong.
Instead of using parseInt(), a better method to use is Math.round(). This method rounds to the nearest int, turning your 919.99999 into 920, giving you the correct answer.

Because JavaScript uses binary arithmetic, floating point math is an approximation of the base 10 result.
One way to avoid this is to perform integral math, but multiplying your decimals up by a factor large enough to transform them to integers and then divide the answer back down by the same factor.
In this case, I'm not sure why you are using parseInt() or parseFloat() since you are not working with strings in the first place.
Lastly, when you do use parseInt() it is advisable to use the second (optional) argument and supply the radix (the base numeral system to be used to perform the operation) as you can get incorrect values back when the string to be parsed begins with "0" or "0x".
var result = parseInt(9.2*10, 10)/10 // returns 9.19
console.log(result);

Related

Convert a string to number with parseInt does not work as expected [duplicate]

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
How to convert a String to long in javascript?
(2 answers)
Closed 10 months ago.
A quick maybe simple question :
We are trying to parse a string into number , the sample number is "1928433000460244141" so when we try to parse it to integer we get 1928433000460244200
const no1 = "1928433000460244141" ;
console.log(parseInt(no1)); // returns 1928433000460244200
what can cause this problem and what is the solution ?
BigInt can be used to store the data , but the problem is we want to send the string converted to number to a service we are using right now , we do not have any access hence it is a 3rd party service so we should handle it from our side.
The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 - 1) and 2^53 - 1.
Source
Because your number is larger than the safe integer limit, you're likely experiencing some floating-point precision issues that are rounding the value off.

round decimals in javascript

I use to round decimal in javascript like this:
lat = e.latLng.lat().toFixed(8);
works most of the times but some times I get more decimals as a result.
For example I get 8.341621100000001 from 8.341621100000001 that means that the number is not rounded. Issue is that I need to save it in the db with a 8 decimals precision and that this values are accepted by an API only with a 8 decimals precision.
How can I fix my code to have always it rounded to 8 decimals. We are talking about latitude and longitudes if it can help. Note that I know about issues with working with decimals in javascript but this seems to me like just an issue about using the wrong tool (sometimes it round sometimes it doesn't).
Thanks!
.toFixed() returns a String representing a rounded number, not a Number. As soon as you continue to use the value like a Number again (thanks to JavaScript's lax conversion rules), you re-enter the realm of floating-point inaccuracy.
If the API accepts strings for the numbers, then just call .toFixed(8) where you pass the value to the API.
You can call .toFixed() then send the result through parseFloat():
parseFloat(8.341621100000001.toFixed(8)); // 8.3416211
Or define a helped function to do it for you:
function clip(value, precision) {
return parseFloat(value.toFixed(precision));
};
clip(8.341621100000001, 8); // 8.3416211

why does javascript Number function return wrong value for this number? [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 6 years ago.
so I ran into this issue with javascript Number() function, it seems to return the wrong value:
the following code:
Number("10153396863200835")
returns 10153396863200836, not 10153396863200835
but if I do Number("10153396863200836") it returns 10153396863200836
and Number("10153396863200834") returns 10153396863200834
so I'm confused what's going on? thanks
Because JavaScript's numbers are IEEE-754 double-precision binary floating point (frequently known as "double"). They have only about 15 digits of decimal precision. Your number, 10153396863200835, is much larger than that.
In doubles, the maximum whole number before we stop being able to represent the next whole number is 9,007,199,254,740,9921. 9,007,199,254,740,993 cannot be represented by doubles; 9,007,199,254,740,994 can. That's because at that scale, the least significant bit is worth 2 decimal. The further you go, the bigger those gaps get, as the least significant bit starts being worth 4 decimal, then 8, then...
Modern JavaScript has a handy constant for the value right before this value, 9,007,199,254,740,991: Number.MAX_SAFE_INTEGER. It's defined as the last whole number in a double where adding 1 gives you the next consequtive whole number. The name is slightly misleading, as 9,007,199,254,740,994 or indeed 10,153,396,863,200,836 aren't going to suddenly stop having those values, it's just that math with them starts getting...interesting.

Why does parsing a large number, of string form, give a larger number? [duplicate]

This question already has answers here:
Why do JavaScript converts some number values automatically
(5 answers)
Closed 7 years ago.
See snippet:
var num = "9223372036854775808";
document.write(num);
document.write("<br>");
document.write(parseInt(num, 10));
On running the code snippet, the first write yields:
9223372036854775808
and the third write yields:
9223372036854776000
But, I am only parsing the number in string form to number. Why does it give a still larger number?
I thought it might have to do something with limits of storage capacity, but then, why would it yield a larger number if it could not store the smaller?
I read this question: Why parsing a very large number to integer return 1 and the parseInt doc but they did not help much.
So, Why does parsing a large number, of string form, return a larger number?
The first result is fine as it is treated as a string.
In the second one, it crosses the value of int which is +/- 9007199254740992 ie, the maximum value which parseint can parse is 9007199254740992 and since your value 9223372036854775808 is larger than the maximum value. it is giving some garbage value.
As commented correctly by blunderboy it seems that that the reason could be this
The numbers in Javascript are 64 bit "double" precision which follow the IEE754 floating point. Sothe largest positive whole number that can therefore be accurately represented is 2^53 and the rest of the remaining bits are reserved for the exponent.
If you check the ECMA specs this has been explained.

Why is an integer literal followed by a dot a valid numeric literal in JavaScript?

In JavaScript it is valid to end an integer numeric literal with a dot, like so...
x = 5.;
What's the point of having this notation? Is there any reason to put the dot at the end, and if not, why is that notation allowed in the first place?
Update: Ok guys, since you mention floats and integers... We are talking about JavaScript here. There is only one number type in JavaScript which is IEEE-754.
5 and 5. have the same value, there is no difference between those two values.
I guess it is just compatibility with other C-like languages where the dot does matter.
You DO need the decimal point if you call a method on an integer:
5.toFixed(n) // throws an error
5..toFixed(n) // returns the string '5.' followed by n zeroes
If that doesn't look right, (5).toFixed(n), or 5.0.toFixed(n), will work, too.
That's a floating point number. Unlike any other language I've ever encountered, all numbers in Javascript are actually 64-bit floating numbers. Technically, there are no native integers in Javascript. See The Complete Javascript Number Reference for the full ugly story.
The correct answer in this case is, that it makes absolutely no difference.
Every number in JavaScript is already a 64bit floating point number.
The ". syntax" is only useful in cases where you can ommit the fixed part because it's 0:
.2 // Will end up as 0.2
-.5 // Will end up as -0.5
So overall it's just saving a byte, but it makes the code less readable at the same time.
What if it wouldn't be an integer, but a floating point literal?

Categories

Resources