Reputation: 91
I'm looking to sum two values i have and then display these as a new UILabel.
I've read online about using float however i'm coming unstuck, here's my code below..
The sum i'm looking to do is : shippingLabel (Shipping Costs) + costLabel (Product Price) then having this then accessible in a new UILabel to display (TotalPrice)
The issue i'm having is that the value's are returning as 00.00
//TotalPrice
// Grab the values from the UITextFields.
float ShippingValue = [[shippingLabel text] floatValue];
float CostValue = [[costLabel text] floatValue];
// Sum them.
float floatNum = ShippingValue + CostValue;
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
TotalPrice = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, 200.0f, 300.0f, 25.0f)];
TotalPrice.textColor = [UIColor colorWithHexString:@"5b5b5b"];
TotalPrice.backgroundColor = [UIColor clearColor];
TotalPrice.font = [UIFont boldSystemFontOfSize:12.0f];
TotalPrice.textAlignment = UITextAlignmentLeft;
[self.view addSubview:TotalPrice];
Upvotes: 0
Views: 908
Reputation: 136
My guess, you are expecting there will be a UILabel with a total number on it,but truth is you see no total number at all. I think here is the problem
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
You are trying to make TotalPrice's text the total number while TotalPrice haven't been allocated, so TotalPrice won't get a thing. You may just put this line after TotalPrice is allocated,it should work. May it help.
Upvotes: 0
Reputation: 130222
It's hard to accurately answer this considering you haven't stated what the problem is exactly. But, the most obvious things that jump out at me are:
1: You are assigning a text value to TotalPrice
before you create it. The lines should appear in the following order.
TotalPrice = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, 200.0f, 300.0f, 25.0f)];
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
2: Your comment indicates that you want to multiply the two values together, but you use an addition operator. This probably isn't your problem, but we all make silly mistakes.
// Multiply them.
float floatNum = ShippingValue * CostValue;
3: The float value of shippingLabel's text maybe inaccurate due to non numerical values in the label's text.
Side note: You should name your variables like this totalPrice
instead of TotalPrice
. It is common practice to use lower case first characters on instances and capitals on classes.
Upvotes: 1