Possible Duplicate:
1/252 = 0 in c#?
hi i have a problem with c#, i want to calculate some things. but when i get a expression like:
decimal test = 3 / 2;
c# says test=1 and not 1.5
how to solve this?
Possible Duplicate:
1/252 = 0 in c#?
hi i have a problem with c#, i want to calculate some things. but when i get a expression like:
decimal test = 3 / 2;
c# says test=1 and not 1.5
how to solve this?
You're using integer arithmetic. If you don't want to do that, make one or both of the operands floating point values, e.g.
decimal test = 3m / 2m;
or
double test = 3d / 2d;
(Only one of the operands has to be a non-integral type, but I believe it's clearer if you can easily make both of them the same.)
You're performing integer math, which truncates. Cast one or both operands to decimal.
decimal test = (decimal)3 / 2;
The above is more applicable if you were using variables as opposed to literal constants, such as int a, b; decimal c = a / b;
You'd need to cast beforehand to avoid integer division.
Otherwise, when using literal constants, append the suffix M
to specify it's a decimal to also avoid integer math.
decimal test = 3M / 2M;
By not doing integer division.
decimal test = (decimal) 3 / (decimal) 2;
When you divide two integers, the result will always be an integer, regardless of the type of the variable in which you store the result.
You can fix this by converting one of the operands to a decimal:
decimal test = 3.0 / 2;
When you give it 3/2 it assumes both as int, calculates only with ints (i.e 3/2=1) and only then takes that 1 and makes it a decimal.
To fix your problem make sure at least the 3 or 2 has a decimal point (i.e 3/2.0)