help a beginner

  • Thread starter Thread starter Mark Reed
  • Start date Start date
M

Mark Reed

I am trying to have two fields, one being a total, the next being a decimal
factor for pecentage. I then want it to calculate the total plus the
percentage factor... for example, 100 is the total, .25 is the
factor...the calculation should come up with 125.

Using the formula below, I get 10025

lbResult.Text = (float.Parse(textBox1.Text)) + (float.Parse(textBox1.Text)
* float.Parse(textBox2.Text)).ToString();

What am I doing wrong?
 
percent means per (divided by) cent (one hundred)

total plus percent is (total * (1 + (percent / 100)))

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Your code just concatenate two strings. First you should sum two float
numbers and then convert to string.

///////////
string tb1 = "100";
string tb2 = "0.25";

string res = (float.Parse(tb1) + float.Parse(tb1) *
float.Parse(tb2)).ToString();

Console.WriteLine(res);
//////////
or

lbResult.Text = (float.Parse(textBox1.Text) + float.Parse(textBox1.Text)
* float.Parse(textBox2.Text)).ToString();


Regards,
Konstantin

Mark Reed said the following on 30.01.2005 9:17:
 
Mark Reed said:
I am trying to have two fields, one being a total, the next being a decimal
factor for pecentage. I then want it to calculate the total plus the
percentage factor... for example, 100 is the total, .25 is the
factor...the calculation should come up with 125.

Using the formula below, I get 10025

lbResult.Text = (float.Parse(textBox1.Text)) + (float.Parse(textBox1.Text)
* float.Parse(textBox2.Text)).ToString();

What am I doing wrong?

You've got brackets in the wrong place. You're calling ToString on the
multiplication side, and then adding that to the floating point value
from the first part. Taking the parsing out makes it clearer what the
problem is. (That's a general rule of thumb, too - if you find that a
complicated line of code doesn't work, split it up into several simple
lines.)

Your code is currently equivalent to:

float total = float.Parse (textBox1.Text);
float factor = float.Parse (textBox2.Text);

lbResult.Text = (total) + (total*factor).ToString();

What you meant was:

lbResult.Text = (total + total*factor).ToString();

However, note that you may well get slightly different answers in some
situations than you expect, due to the vagaries of floating point
arithmetic. See
http://www.pobox.com/~skeet/csharp/floatingpoint.html
 
Back
Top