2015-02-19 4 views
0

У меня возникли проблемы с моим приложением я пытаюсь умножить 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];  

Спасибо!

+0

Пробовали ли вы использовать 'NSLog()', чтобы увидеть фактическое значение 'total'? Похоже, что текст в ваших ярлыках отформатирован в разных валютах? (Доллар США против бразильского реального?) –

+0

Кроме того, «.» vs. "," как маркер десятичной точки указывает на разницу в локали между Xcode и устройством. Было бы неплохо, если бы кто-нибудь, кто разбирался в форматировании чисел и локалях iOS, мог добавить некоторые подробности ... (я так и не получил его полностью) –

+0

Здравствуйте, @NicolasMiari, новичок в sdk. но я думаю, что проблема в локали. Я собираюсь сдаться. единственное, что я хотел, это умножить значение числа *, чтобы узнать общий счет, который вы понимаете? – ViniciusPV

ответ

0

Вместо использования [self.quantos.text doubleValue], попробуйте использовать [[номерFormatter номерWithString: self.quantos.text] двойнойValue].

То же самое для ценыPerIten.

EDIT:

Вот некоторые примеры кода:

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); 
+0

, тогда код будет выглядеть так: NSNumber * total = [NSNumber numberWithDouble: (([[numberFormatter numberWithString: self.quantos.text] doubleValue]) * [[numberFormatter numberWithString: self.pricePerIten.text] doubleValue])) ]; ??? – ViniciusPV

Смежные вопросы