Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to divide a/b and show the result in decimal
for eg: i am dividing 10/3 and the result should come 3.3333 but mine project shows 3 only what can i do.
i am writing mine code as
C#
outputtextblock1.Text = Convert.ToString(Convert.ToInt32(Decimal.Parse(cf1.Text))/Convert.ToInt32(Decimal.Parse(cf2.Text)));
Posted
v2

When you divide two integers, you'll get only the integer part of that division.
The easiest way to change it is:
C#
decimal a = 10 / (decimal)3;

You can also put an "m" after a number to indicate it's a decimal type. If you wanted to convert it to float or double, you use "f" instead.
Example:
C#
decimal a = 10 / 3m;

You can also call Convert functions:

C#
decimal a = 10 / Convert.ToDecimal(3);

In these cases it's only needed to cast only one of your values, as both variables are numeric.
In your code, on the other hand, you'll need to cast both as you can't divide a string.

Applying that to your code, it could be something like this:

C#
outputtextblock1.Text = (Convert.ToDecimal(cf1.Text) / Convert.ToDecimal(cf2.Text)).ToString()

Or maybe like this:
C#
outputtextblock1.Text = (Decimal.Parse(cf1.Text) / Decimal.Parse(cf2.Text)).ToString();


I hope this helps. :)
 
Share this answer
 
v4
Comments
Keshav Gyawali 26-Nov-12 10:48am    
Thank you so much
it really works....
entilete 26-Nov-12 16:30pm    
You're welcome :)
I added more examples that I forgot to add before.
You are converting both the dividend and divisor to Int32 and then performing the division, hence a integer division is performed.
You may, for instance, remove the Convert.ToInt32 calls.
 
Share this answer
 
Hello,

You could do it like this:

C#
string a = "10";
string b = "3";

double result = double.Parse(a) / double.Parse(b);

outputtextblock1.Text = result.ToString();



Valery.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900