+ 1
JS Parts divided from sum, not equal to sum when counted (with 2 decimals)
In JavaScript I’m trying to divide sum with 2 decimals into equal amounts. Then when I count all of the divided amounts, the amount is higher than it should be, because of 3rd decimal number being rounded up. Example: var a = 6; // Number of payments var b = 479.25 // Sum var c = (b/a).toFixed(2); // var c = 79.875, which is rounded to 79.88 And then 6* 79.88 ofcourse becomes 479.28 which is 3 more than it should be. Any ideas how to solve this? Any help is greatly appreciated. Thank you Coders.
9 Antworten
+ 2
These are two different things because in the variables are right values and toFixed only rounds the result as you can see here. Var c is not equal 79.88.
var a = 6; // Number of payments
var b = 479.25 // Sum
var c = (b/a); //.toFixed(2); // var c = 79,88
console.log(c)
console.log(a*c)
console.log(6*79.88);
+ 1
Use dot replace comma
+ 1
// ohh get you F.M.
function round(num, dig) {
dig = Math.pow(10, dig);
return Math.round(num * dig) / dig;
}
console.log(round(79.875, 2));
+ 1
See, I’m trying to write a code, that divides total sum(in this case479,25, but I hve different amount) into 6 different payment installments (sometimes it’s 3 installments)
Divided numbers could also be outputed like this:
80, 80, 80, 80, 80, and 79,25.
I just don’t know the way to achieve this.
Sorry, if I’m not able to explain myself well enough, since I’m a newcomer😊
Basel.Al_hajeri?.MBH()
CamelBeatsSnake
+ 1
No problem F.M. you can chat with me anytime if you need any help with JS any topic
0
No, that is not it. Look at the question again, please.
0
You're essentially asking why dividing a number n by x, then changing the result by using toFixed, then multiplying by x again doesn't get you n again.
It's because you're changing it by using toFixed.
If you don't do that, you'll get 479.25 at the end.
0
Yes, but, I have to display only two decimals for those divided amounts. If I don’t use it, The result is 79,875, which doesn’t work for me.
0
F.M. Then you need to separate the display logic. Do whatever rounding you need to do for displaying, but use the non rounded values for the other calculations.