iphone - 在 iOS 中使用 float 添加值

标签 iphone ios math floating-point

我希望对我拥有的两个值进行求和,然后将它们显示为新的 UILabel。

我在网上阅读了有关使用 float 的内容,但是我遇到了困难,下面是我的代码..

我想要做的总和是:shippingLabel(运费)+ costLabel(产品价格),然后在新的 UILabel 中访问它以显示(TotalPrice)

我遇到的问题是该值返回为 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];

最佳答案

考虑到您还没有说明问题到底是什么,很难准确回答这个问题。但是,最明显的事情是:

1:您在创建 TotalPrice 之前为其分配一个文本值。这些行应按以下顺序出现。

TotalPrice = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, 200.0f, 300.0f, 25.0f)];
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];

2:您的注释表明您想要将两个值相乘,但您使用了加法运算符。这可能不是你的问题,但我们都会犯愚蠢的错误。

// Multiply them.
float floatNum = ShippingValue * CostValue;

3:由于标签文本中的非数字值,shippingLabel 文本的浮点值可能不准确。

旁注:您应该将变量命名为 totalPrice,而不是 TotalPrice。通常的做法是在实例上使用小写第一个字符,在类上使用大写字母。

关于iphone - 在 iOS 中使用 float 添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17005422/

相关文章:

iphone - 核心数据 : How to model multiple one-to-many between two entities

iphone - UIButton 选定状态在 iOS 7 中不起作用

ios - 如何在按下主页按钮后重置 ViewController 并返回到同一个 ViewController

jquery - mouseMove 上的水平滚动 - 较小 div 中的宽 div 并溢出 :hidden (Can't get the math to work)

javascript - 当显示器屏幕分辨率不是方形时,如何绘制圆形而不是椭圆形?

javascript - 添加 Javascript 变量

ios - 从 SKscene (SpriteKit) 呈现 UIViewController

iphone - objective-c 源 locationManager 在自己的类中

ios - TableView 错误 Swift 2

ios - Ad hoc iOS应用-不带iTunes分发