开发者

NSNumberformatter adding decimal places

I export some floatvalues into a Textfile (JSONFormat) then import it again into my project. Weirdly, the NSNumberformatter takes the Strings and adds some random(?) decimal places on its own....

This is what I get from NSLog:

[9697:207] f1 150.837296   -  f2 150,8373 
[9697:207] f1 160.746902   -  f2 160,7469
[9697:207] f1 150.242599   -  f2 150,2426
[9697:207] f1 160.068893   -  f2 160,0689
[9697:207] f1 149.451096   -  f2 149,4511
[9697:207] f1 159.154205   -  f2 159,1542

As you can see, the values to the right are my input strings(f2) and the values to the left are my floats (f1).

Heres my code:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setDecimalSeparator:@","];

float f1 = (float)[[formatter numberFromString:[mutableArray objectAtIndex:i]] floatValue];

Any ideas why this is happe开发者_如何学Goning?


Cause of this effect is in float type, because float is imprecise type.

See examples below:

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setDecimalSeparator:@","];

float f1 = [[formatter numberFromString:@"150,8373"] floatValue];
NSLog(@"%.8f", f1); //150.83729553
NSLog(@"%.4f", f1); //150.8373 - formatting hides a tail

double f1 = [[formatter numberFromString:@"150,8373"] double];
NSLog(@"%.8f", f1); //150.83730000

So, use double for getting right precision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜