Reputation: 851
Our quality-assurance team detect a defect. When they write 0.095
or 0,095
in a currency field, the NSNumberFormatter
converts the content to 95
.
This is the code we're using:
+ (NSNumber *) getNumberWithDecimalFromString:(NSString*) theSource
{
if ([TSCommons isEmpty:theSource])
return [[NSNumber alloc] initWithInt:0];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
if ([theSource rangeOfString:@","].location != NSNotFound) {
[formatter setDecimalSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];
} else if ([theSource rangeOfString:@"."].location != NSNotFound) {
[formatter setDecimalSeparator:@"."];
[formatter setCurrencyDecimalSeparator:@"."];
}
NSNumber *tmp = [formatter numberFromString:theSource];
[formatter release];
return [tmp retain];
}
The locale is es_ES
Any idea about this unexpected behavior?
To introduce more information about this problem, because come back again after the last XCode update I prepared a test
- (void) testNumberFormatter
{
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1"] doubleValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,12342"] doubleValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,12"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,123"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1234"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1234234"] doubleValue]);
}
The result on the Console is the following:
41.100000
41.123420
41.119999
41123.000000
41.123402
41.123423
Thanks!!
Upvotes: 1
Views: 279
Reputation: 3400
NSString* theSource = @"0.095";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
if ([theSource rangeOfString:@","].location != NSNotFound) {
[formatter setDecimalSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];
} else if ([theSource rangeOfString:@"."].location != NSNotFound) {
[formatter setDecimalSeparator:@"."];
[formatter setCurrencyDecimalSeparator:@"."];
}
NSNumber *tmp = [formatter numberFromString:theSource];
NSLog(@"get Number %@ - %lf %lf", tmp, [theSource doubleValue], [tmp floatValue]);
// output get Number 0.095 - 0.095000 0.095000
Upvotes: 0