Sum with decimal types

  • Thread starter Thread starter Alberto
  • Start date Start date
A

Alberto

Actually I have two quantities (4.61) stored as decimal numbers.
Why if I try to sum them the result is 9.23 if the correct value is 9.22?

Thank you
 
Because if you use + there an implicit convertion where it rounds to the
nearest integer value. If you want to sum 2 decimals you should use the static
method "Add" which will undestand that you are dealing with decimal types.

System.Decimal d = System.Decimal.Add(4.61m, 4.61m);
result is 9.22

HTH,

Erick Sgarbi
www.blog.csharpbox.com
 
Are they stored as Decimal or as Single or Double?

When I use this code:

Dim s1, s2 As Decimal

s1 = 4.61D
s2 = 4.61D

MsgBox("Sum: " & (s1 + s2).ToString)

I get 9.22 as expected
 
My first thought would be that both values are actually somewhere between
4.61 and 4.6149999. It may be that the numbers originated as doubles or
double constants and were explicitly converted to decimal someplace in your
code.

Be sure to use the "M" or "m" suffix for literal values being assigned to
decimal variables, e.g., 4.61M or 4.61m. Although supposedly there are no
implicit conversions in C# to the decimal type, 4.61 by itself will I
believe be interpreted as a double and then assigned to the decimal
variable, which may constitute an "explicit" conversion. I haven't checked,
but it wouldn't surprise me.

If you view the variables in the debugger, what numbers do you see in there?

--Bob
 
Because if you use + there an implicit convertion where it rounds to the
nearest integer value.
Are you sure?
When I try

decimal d1 = 4.61m;
decimal d2 = 4.61m;
decimal d = d1 + d2;

it works as expected.
Of course if you were to try and add int and decimal it would but
decimal and decimal?

Cheers
JB
 
Because if you use + there an implicit convertion where it rounds to the
nearest integer value.

No there isn't - not if either side is actually a decimal. If it were
rounding to the nearest *integer* value, the result wouldn't be 9.23,
would it?
 
My first thought would be that both values are actually somewhere
between 4.61 and 4.6149999. It may be that the numbers originated as
doubles or double constants and were explicitly converted to decimal
someplace in your code

My thoughts exactly...


HTH,

Erick Sgarbi
www.blog.csharpbox.com
 
Back
Top