problem converting to decimal

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?
 
K

Kalpesh Shah

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

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.
 
C

Christof Nordiek

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
 
J

Jon Skeet [C# MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top