2021年4月12日星期一

How to divide a decimal number into rounded parts that add up to the original number?

All Decimal numbers are rounded to 2 digits when saved into application. I'm given a number totalAmount and asked to divide it into n equal parts(or close to equal).

Example :

Given : totalAmount = 421.9720; count = 2 (totalAmount saved into application is 421.97)  Expected : 210.99, 210.98 => sum = 421.97  Actual(with plain divide) : 210.9860 (210.99), 210.9860 (210.99) => sum = 412.98  

My approach :

var totalAmount = 421.972m;  var count = 2;  var individualCharge = Math.Floor(totalAmount / count);  var leftOverAmount = totalAmount - (individualCharge * count);  for(var i = 0;i < count; i++) {      Console.WriteLine(individualCharge + leftOverAmount);       leftOverAmount = 0;  }  

This gives (-211.97, -210)

https://stackoverflow.com/questions/67067274/how-to-divide-a-decimal-number-into-rounded-parts-that-add-up-to-the-original-nu April 13, 2021 at 08:33AM

没有评论:

发表评论