Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running this calculation adds an extra decimal point

I’m running the following calculation and for some reason, an extra decimal is added to the result:

decimal bal = 10.0000
decimal totAmount = 15.0000
decimal payAmount = 3

tempAmount = Math.Ceiling((decimal)(bal / totAmount) * payAmount * 100);
tempAmount = tempAmount / 100;

// tempAmount results in 2.01 as opposed to 2.00

Am I running this incorrectly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Am I running this incorrectly?

No, but you’re introducing an intermediate value (10/15) which can’t be precisely represented as a decimal. It’s being rounded up to 0.6666666666666666666666666667, which then leads to the problem.

If you perform the division as the last operation, you can avoid that, at least in this case:

using System;

decimal bal = 10.0000m;
decimal totAmount = 15.0000m;
decimal payAmount = 3;

decimal tempAmount = Math.Ceiling((bal * payAmount * 100m) / totAmount);
tempAmount = tempAmount / 100;

Console.WriteLine(tempAmount);

That prints out 2 instead of 2.01.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading