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

16th Apr 2021, 2:02 PM
F.M.
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);
16th Apr 2021, 2:26 PM
JaScript
JaScript - avatar
+ 1
Use dot replace comma
16th Apr 2021, 2:16 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 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));
16th Apr 2021, 2:41 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 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
16th Apr 2021, 2:41 PM
F.M.
+ 1
No problem F.M. you can chat with me anytime if you need any help with JS any topic
16th Apr 2021, 2:51 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
0
No, that is not it. Look at the question again, please.
16th Apr 2021, 2:19 PM
F.M.
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.
16th Apr 2021, 2:27 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
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.
16th Apr 2021, 2:33 PM
F.M.
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.
16th Apr 2021, 2:38 PM
CamelBeatsSnake
CamelBeatsSnake - avatar