Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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
outputtextblock1.Text = Convert.ToString(Convert.ToInt32(Decimal.Parse(cf1.Text))/Convert.ToInt32(Decimal.Parse(cf2.Text)));
Posted 26-Nov-12 3:29am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

When you divide two integers, you'll get only the integer part of that division.
The easiest way to change it is:
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:
decimal a = 10 / 3m;
You can also call Convert functions:
 
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:
 
outputtextblock1.Text = (Convert.ToDecimal(cf1.Text) / Convert.ToDecimal(cf2.Text)).ToString()
Or maybe like this:
outputtextblock1.Text = (Decimal.Parse(cf1.Text) / Decimal.Parse(cf2.Text)).ToString();
 
I hope this helps. Smile | :)
  Permalink  
v4
Comments
Keshav Gyawali at 26-Nov-12 10:48am
   
Thank you so much
it really works....
entilete at 26-Nov-12 16:30pm
   
You're welcome :)
I added more examples that I forgot to add before.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Hello,
 
You could do it like this:
 
string a = "10";
string b = "3";
 
double result = double.Parse(a) / double.Parse(b);
 
outputtextblock1.Text = result.ToString();
 
 

Valery.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 489
1 ChintanShukla 295
2 RyanDev 250
3 Richard Deeming 250
4 Sergey Alexandrovich Kryukov 218
0 Sergey Alexandrovich Kryukov 8,906
1 OriginalGriff 7,601
2 CPallini 2,603
3 Richard MacCutchan 2,121
4 Abhinav S 1,923


Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 26 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100