Reputation: 88
I have been working on this for two days now. Time to consult stackoverflow.
I have an iOS user setting that allows selection of the decimal and grouping separators. It works perfectly when the separator is a decimal point, but when set to a decimal comma all the numerical entries are automatically rounded to the nearest whole number and any calculations lose precision.
The scheme is this:
//Use formatter to set decimal style for output
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:1];
[formatter setMaximumFractionDigits:5];
//Set number format from preferences
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *numberFormat = [userDefaults stringForKey:kNumberFormat];
if([numberFormat isEqualToString:@"Decimal Point"])
{
[formatter setDecimalSeparator:@"."];
[formatter setGroupingSeparator:@","];
}
else
{
[formatter setDecimalSeparator:@","];
[formatter setGroupingSeparator:@"."];
}
NSNumber *number = [NSNumber numberWithDouble: result];
NSString* formattedResult = [formatter stringFromNumber:number];
[display_ setText: [NSString stringWithFormat:@"%@", formattedResult]];
[formatter release];
In decimal separator mode 5.5 + 5.5 = 11.0
But, in comma separator mode 5.5 is immediately truncated to 5.0 in the display and 5.5 + 5.5 = 10.
Not what I want!
Upvotes: 1
Views: 4265
Reputation: 88
I was able to figured it out on my own. The number formatter was operating correctly. To get my analyzer class to work I had to send it a double that could not contain a comma decimal separator. But to get the display to look right in comma separator mode I had to send the string in the desired format to the display (e.g. 2.500,05), then reformat the string with a decimal points and commas as needed and then send that string to the analyzer as a double (e.g. 2,500.05). A little tricky since I am essentially swapping the decimal points and the commas. There is probably a slicker way to do it but this worked:
NSString *numberFormat = [userDefaults stringForKey:kNumberFormat];
//if the string has been entered using a decimal comma, do this
if([numberFormat isEqualToString:@"Decimal Comma"])
{
NSString *displayString = [display_ text];
NSString *newStringValue = [displayString
stringByReplacingOccurrencesOfString:@"," withString:@"x"];
newStringValue = [newStringValue
stringByReplacingOccurrencesOfString:@"." withString:@","];
newStringValue = [newStringValue
stringByReplacingOccurrencesOfString:@"x" withString:@"."];
[display_ setText:displayString];
[[self analyzer_] setFirstOperand:[newStringValue doubleValue]];
}
//there is no problem if the decimal separator is a decimal point, so
//just send it as is
if([numberFormat isEqualToString:@"Decimal Point"])
{
[[self analyzer_] setOperand:[[display_ text] doubleValue]];
}
Upvotes: 1