为什么不同的值,但具有相同的代码

时间:2015-02-19 01:06:07

标签: ios xcode

我的应用程序出现问题我尝试将2个 UITextField 值相乘以得到 UILabel 的结果。但是当我在模拟器上运行应用程序时,乘法和结果是可以的但是当我在我的iDevice中运行时结果是不同的,因为它不能识别我的国家(巴西)中使用的小数点的“点”值(货币)我认为。

下面的图片可以看到差异: an image below to see the difference 我正在使用的代码是:

//create NSNumberFormatter to be able to show currency
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMaximumFractionDigits:2];

//Calculate total cost of trip
NSNumber *total = [NSNumber numberWithDouble:(([self.quantos.text doubleValue]) * [self.pricePerIten.text doubleValue])];

//Set the total cost label
self.totalCost.text = [numberFormatter stringFromNumber:total];    

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用[[numberFormatter numberWithString:self.quantos.text] doubleValue]而不是[self.quantos.text doubleValue]。

pricePerIten相同。

编辑:

以下是一些示例代码:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMaximumFractionDigits:2];

NSLog(@"Locale: %@", numberFormatter.locale.localeIdentifier);

// I don't know how you are constructing the text that you display
// in the text fields, so these two lines are just for testing purposes
NSString *quantityString = [numberFormatter stringFromNumber:@(2.50)];
NSString *priceString = [numberFormatter stringFromNumber:@(3)];

NSLog(@"Quantity string: %@", quantityString);
NSLog(@"Price string: %@", priceString);

// Use your formatter to convert the input strings to
// an NSNumber and then double
double quantity = [[numberFormatter numberFromString:quantityString] doubleValue];
double price = [[numberFormatter numberFromString:priceString] doubleValue];

double total = quantity * price;

NSLog(@"Quantity double: %f", quantity);
NSLog(@"Price double: %f", price);
NSLog(@"Total double: %f", total);

// Now convert the total back to an NSNumber...
NSNumber *totalNumber = [NSNumber numberWithDouble:total];

// ...and then to a string for display
NSString *totalString = [numberFormatter stringFromNumber:totalNumber];

NSLog(@"Total string: %@", totalString);