1

I'm using the below formula to try and get an interest rate but it is sometimes coming up a penny short

dim float as decimal = Math.ROUND((((Convert.ToDecimal(35000000.00) * Convert.ToDecimal(0.020625)) / 360) * 3), 2, MidpointRounding.AwayFromZero)

This is equaling 6015.62...if i do the math on a calculator I get 6015.625 which I would then want to round up to 6015.63...how can I achieve this?

ertuu85
  • 79
  • 1
  • 6
  • Possible duplicate of [What is wrong with Math.Round() in VB.Net?](https://stackoverflow.com/questions/14835001/what-is-wrong-with-math-round-in-vb-net) – MatSnow Aug 07 '18 at 14:09
  • Your formula returns 6015.6249999999999999999999999, not 6015.625. You end up with 35000000 * 0.020625 / 360 = 2005.2083333333333333333333333 then you have * 3 – the_lotus Aug 07 '18 at 14:14

1 Answers1

2

It's not a rounding problem. Your formula returns 6015.6249999999999999999999999, not 6015.625.

35000000.00 * 0.020625 = 721875
721875 / 360 = 2005.208333333333
2005.208333333333 * 3 = 6015.624999999999

If you change your formula to

(35000000.00 * 0.020625) / (360 / 3)

Then you get

35000000.00 * 0.020625 = 721875
360 / 3 = 120
721875 / 120 = 6015.625

Even if you change the order you'll get what you want.

35000000.00 * 0.020625 * 3 / 360

Calculators sometime do fancy things. But the compiler does one step at a time and doesn't look at what was done previously.

the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • Ah I see...is there a way to round 6015.6249999999999999999999999 to 6015.63 then? as that would round to 6015.625 and then round to 6015.63? – ertuu85 Aug 07 '18 at 14:46
  • I wouldn't recommend a way to do that because it could change other result. I would just change the order of operation like do division last, or simplified 360/3. – the_lotus Aug 07 '18 at 14:59
  • Changed the formula to `Math.Round((((Convert.ToDecimal(Amount) * Convert.ToDecimal(Rate))) * (DaysProcessed / 360)), 2, MidpointRounding.AwayFromZero)` – ertuu85 Aug 07 '18 at 15:53
  • @ertuu85 - updated my answer (you can also change from decimal to double - less precise). – Sebastian Brosch Aug 07 '18 at 15:56