I have 3 TextBox.
I input 123.45 into the TextBox1, input 123.22 into the TextBox2, then do a calculation (123.45 + 123.22)/2 = 123.335.
I want to display the result 123.34 instead of 123.335 in the TextBox3.
How to do that?
Appreciate for your help!
I input 123.45 into the TextBox1, input 123.22 into the TextBox2, then do a calculation (123.45 + 123.22)/2 = 123.335.
I want to display the result 123.34 instead of 123.335 in the TextBox3.
How to do that?
Appreciate for your help!

Krishnaraj L153 reputationPosted Jun 30, 2006, 5:19 AM EDT
Try this code it should work.
decimal
dVal = Convert.ToDecimal (textBox1.Text) + Convert.ToDecimal (textBox2.Text);dVal = dVal / 2;
textBox3.Text = Convert.ToString ( Math.Round (dVal, 2) );
f117_b28 reputationPosted Jul 3, 2006, 6:21 AM EDT
It works like charm.
Krishnaraj L153 reputationPosted Jul 3, 2006, 6:26 AM EDT
f117_b28 reputationPosted Jul 7, 2006, 6:28 AM EDT
In most cases, it works fine. Try this two numbers out, (10982.63 + 8453.78)/2 = 9718.205.
Math.Round (dVal, 2) returns 9718.2, not 9718.21.
Any ideas?????
Solitaire85 reputationPosted Jul 7, 2006, 6:36 PM EDT
The function is using a form of banker's rounding. Instead of rounding up from .205 to .21, it is rounding to the nearest EVEN digit.
For example, if the number ends with either .215 or .225, it returns .22 for both of them.
You can fix this problem by adding .005 to the number before rounding:
dval = Math.Round(dval + 0.005, 2)
Now .205 will round to .21
hasan maqbool2 reputationPosted Jul 8, 2006, 5:49 AM EDT
decimal
ans = 0; try{
ans =
Convert.ToDecimal(textBox2.Text) + Convert.ToDecimal(textBox3.Text);ans = ans / 2;
this.textBox1.Text = Convert.ToString(Math.Round(ans, 2,MidpointRounding.AwayFromZero));}
catch (System.FormatException){
MessageBox.Show("Format is not consistent");}
Try it.
f117_b28 reputationPosted Jul 10, 2006, 2:44 PM EDT
Thank both Solitaire and hasan maqbool very much.
To Solitaire: Your stuff solves my problems.
To hasan maqbool: I am running .Net Framework v1.1. So I think the thing MidpointRounding.AwayFromZero works only with v2.0, which I don't have it yet.