This question already has answers here:
Why does changing the sum order returns a different result?
(7 answers)
In which order should floats be added to get the most precise result?
(11 answers)
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 months ago.
Quick summary - I was running a piece of code(in React application) where I am summing up decimal values entered by a user. One of the conditions to move to next page is if the sum equals 100
Problem - In one case, the sum of all values (a+b+c+d+e+f) is being computed to 99.99999999999997 even though the summation(over a calculator) is 100. But when I change the summation order to a+d+e+f+b+c, the sum is correctly computed to 100.
Please find below code samples -
Wrong summation -
const result = [15+10.4+1.9+1.9+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //99.99999999999997
Correct summation -
const result = [15+10.4+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15+1.9+1.9].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //100
Questions -
How does JavaScript engine compute?
How to compute to 100 always (without using ceil, floor or round methods because Math.round(99.6) is also equal to 100.
Related
This question already has answers here:
Generate unique random numbers between 1 and 100
(32 answers)
Closed 2 years ago.
I feel like this should be an easy exercise:
1.- Generate 10 random numbers (0-99) and storage in an array.
2.- Numbers should not repeat.
But all the answer I get from the internet are very complicated or excessive long code.
In the code below I already generate the 10 numbers, but they keep repeating. Any ideas?? (i tried If/else but it didn't work) :(
numbers=[]
for(i=0;i<10;i++){
var oneRandomNum = Math.floor(Math.random()*100);
numbers.push(oneRandomNum);
}
console.log(numbers);
Thank you so much!!!!! :)
You can repeatedly add numbers to a Set, and stop when its size reaches 10:
const set = new Set();
while (set.size !== 10) {
set.add(Math.floor(Math.random() * 100));
}
const numbers = [...set];
console.log(numbers);
This question already has answers here:
Is floating point math broken?
(31 answers)
Precise Financial Calculation in JavaScript. What Are the Gotchas?
(8 answers)
Closed 5 years ago.
I have a piece of code that is pulling data from a SharePoint list from I'm using SPServices and this code then pulls from the Spent column and adds up all the numbers and then puts it in an array however I'm getting some weird results.
none of the numbers it pulls through have more than 2 decimal places(it's a finance column) however I'm getting totals like 57062.229999999996 and 151704.58000000002
I've tried using .toFixed(2) on to mynumber and parseFloat(SpentFix)
and then converting back to a number and I get the same results.
Also the reason why I have a .substring(7) is because the spend column is a computed field so when pulling data float,# is a the start of each entry for some reason
if anyone can help that would be great.
var SpentFix = $(this).attr("ows_Spent").substring(7);
if (SpentFix != undefined) {
var mynumber = parseFloat(SpentFix)
SLarray[counter][1] += mynumber;
}
This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
I'm trying to decrement "0.01" from a number, it works fine the first time, but when I try to decrement one more time it adds some extra numbers.
Here is my JavaScript code:
function decrement() {
var credits_sidebar = $('#credits_sidebar').html();
var credits_update = credits_sidebar - 0.01;
$("#credits_sidebar").fadeOut('');
$("#credits_sidebar").html(credits_update);
$("#credits_sidebar").fadeIn('');
}
If you click once on the decrement button it works, but if you click another time, the number will be "95.97999999999999" it should be 95.98 instead.
Here's an example JsFiddle:
https://jsfiddle.net/rozvnay1/
var credits_update = (credits_sidebar - 0.01).toFixed(2)
JSFiddle demo: https://jsfiddle.net/8eakhn4L/1/
This is a problem with floating point value representation.
You should consider using
Math.round((credits_sidebar - 0.01)* 100)) / 100
This behavior is normal and expected because of the way floating point math is done in JavaScript.
However what you simply can do is multiply your number by a factor of 100 to make it a whole number that needs to be decremented then you can do the decrement and divide the result by 100 to get the correct decimal answer.
You need to update this for working of code:
var credits_update = (credits_sidebar - 0.01).toFixed(2);
This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
i'm currently trying to store data via localstorage on my website, and if for example I do so :
localStorage.setItem("vue",10206726906969851)
When I want to get the value back I get this result :
localStorage.getItem("vue")
-> "10206726906969852"
So why does the value changes ? Thank you in advance for your help
JavaScript is not epic at precision with numbers. An example:
.2 + .2 = .4
but
.2 + .2 + .2 = 0.6000000000000001
The number you are using is too big for JS to maintain good precision on it. Log the following in your console and you will see what I mean.
10206726906969851 > Number.MAX_SAFE_INTEGER // returns true
The number you are using is too big. I have experienced this in the past. The server will give me numbers that are fine for Java, but too large for JavaScript. So... JS will mess them all up. The only way to fix was to get a shorter number that JS wouldn't barf on.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Elegant workaround for JavaScript floating point number problem
If I perform the following operation in Javascript:
0.06120*400
The result is 24.48.
However, if I do this:
24.48/400
The result is:
0.061200000000000004
JSFiddle: http://jsfiddle.net/zcDH7/
So it appears that Javascript rounds things differently when doing division and multiplication?
Using my calculator, the operation 24.48/400 results in the correct answer of 0.0612.
How should I deal with Javascript's inaccurate division? I can't simply round the number off, because I will be dealing with numbers of varying precision.
Thanks for your advice.
You can get the correct result with simply using:
var a = 24.48/400;
console.log(a.toFixed(6));
And because typeof a.toFixed(6) === 'string' you can:
var a = 24.48/400;
console.log(parseFloat(a.toFixed(6)));
The argument of toFixed is the number of decimals you want.