problem converting to decimal

  • Thread starter Thread starter Jeff
  • Start date Start date
J

Jeff

Hey

..NET 2.0

In my code am I trying to convert an int value into a decimal:

decimal d = 0;
int k = 87664;
d = Convert.ToDecimal(k/100);

The last line of code gives d the value 876, instead I want it to be 876,64

any suggestions?
 
Jeff,

I haven't written sample code to test your example.
However, 87664/100 will give you 876 (an int divided by an int returns
an int)

So, change the line to k/100.0 & it might work.

Kalpesh
 
Hi,

Try:

d = Convert.ToDecimal( (double)k/100);


The problem is that you are dividing two integers, the result of that is an
integer also, and is this later integer the one you are converting to
Decimal.
 
Jeff said:
Hey

.NET 2.0

In my code am I trying to convert an int value into a decimal:

decimal d = 0;
int k = 87664;
d = Convert.ToDecimal(k/100);

The last line of code gives d the value 876, instead I want it to be
876,64

The argument of ToDecimal() allready has no fractional part, and it isn't
restored bay the conversion.

You should do the conversion prior to the division:

d = (decmimal)k/100;

Christof
 
Try:

d = Convert.ToDecimal( (double)k/100);

The problem is that you are dividing two integers, the result of that is an
integer also, and is this later integer the one you are converting to
Decimal.

However, that involves converting to a double which will probably make
it pointless using decimal in the first place.

We want to do decimal division, not double division. I would do:

int k = 87664;
decimal d = k/100m;

Jon
 
Back
Top