0

I have scanned a large number of questions and answers around math.round /.floor/.truncate/.ceiling but couldn't find a clear answer to my problem of rounding (with currency values).

I understand math.round / toeven / awayfromzero but that doesn't seem to do it.

( in the following examples 1.88 is just any number an can be replaced with any other n.mm value)

If the result of a calculation of "decimal / decimal" is 1.88499 I need 1.88 as the rounded result. If the calculation gives 1.885499 I want 1.89 as the result of rounding (always rounding to two decimal digits).

Now, math.round(1.88499999,2) Returns 1.89 though 0.00499999 is certainly BELOW the middle between 8 and 9. I understand that if the number is rounded from the last decimal digit up to the first, the result is understandable:

1.88499999 -> 1.8849999 -> 1.884999 -> 1.88499 -> 1.8849 -> 1.885 -> 1.89

However, from a fiscal Point of view, like for VAT calculations, that doesn't help at all.

The only way i can think of is to cut the number first behind the third decimal digit to round it then to 2 required digits. But isn't there a more elegant way?

A_Sk
  • 4,532
  • 3
  • 27
  • 51
Herbert
  • 151
  • 2
  • 12
  • Math.Round(1.88499999,2) returns 1.88 – Hamid Pourjam Sep 12 '15 at 12:52
  • usually, you shouldn't use float or double for any calculation involving money in any programming language (because of the way float and double work, they are imprecise), there are libraries specifically made to handle such operation. try searching for them. u need a fixed point arithmetic library (that has features to handle currency) – x4rf41 Sep 12 '15 at 12:56
  • are you by any chance using float? that would explain why `1.88499999` rounds to 1.89` – x4rf41 Sep 12 '15 at 13:05
  • true, `1.88499999` wasn't used in round as constant, it was the result of a Division by two decimals – Herbert Sep 12 '15 at 13:11

2 Answers2

0

you can use Decimal.ToString() ,

try,

decimal dec = 1.88499999m;

dec = Convert.ToDecimal(dec.ToString("#.00"));
A_Sk
  • 4,532
  • 3
  • 27
  • 51
0

I have solved the issue by avoiding the float datatypes in the case.

I did use integer variables and multiplied all currency values by 100. This way the calculations are not dependend on rounding or rather are rounded correctly when the result of a calculation is set into an integer.

Herbert
  • 151
  • 2
  • 12