Вопрос

I start off with a number, lets say 250. I add all sorts of numbers, but anytime I add a high number like 2,000 it adds correctly. Then I add 3. The new number comes out to 5 like it thought 2,000 was 2.0. I do not know why it is doing this.

float start = self.amountLabel.text.floatValue;
float changeAmount = self.amountField.text.floatValue;
float newValue;
if (determConfirm == 1) {
    newValue = start + changeAmount;
} else {
    newValue = start - changeAmount;
}

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

[formatter setMaximumFractionDigits:5];

[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:newValue]];

[[NSUserDefaults standardUserDefaults] setValue:numberString forKey:@"newValue"];
[[NSUserDefaults standardUserDefaults] synchronize];

self.amountLabel.text = numberString;
self.amountField.text = @"0.00";
[self.amountField resignFirstResponder];
Это было полезно?

Решение

The problem is the use of floatValue to convert the formatted number text to a number. floatValue only works as expected if the text is unformatted (no commas) and uses the period for the decimal separator.

Since you store a formatted number in the field, it only works with small numbers and in certain locales.

Replace your use of floatValue on the text with the same NSNumberFormatter used to format the number. Use it to parse the text and give you an NSNumber (which you can then call floatValue on).

Другие советы

Just a guess as it's hard by looking at your code, but maybe you want this:

float newValue = start;

if (determConfirm == 1) {
    newValue += changeAmount;
} else {
    newValue -= changeAmount;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top