在-floatValue
评论声明中显示:
/* 以下便捷方法都跳过初始空格字符(whitespaceSet)并忽略尾随字符。NSScanner 可用于更“精确”的数字解析。*/
因此,逗号会导致截断,因为它们是尾随字符。甚至您提供的字符串 (123,456,789) 也只打印 123.000,因为这都是可见的-floatValue
。
//test
NSString *string = @"123,456,789";
float originalValue2 = [string floatValue];
NSLog(@"datacellR2C2 as text --> %@ <---\n",string); // this correctly shows the value in datacellR2C2
NSLog(@"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:16:15.913 [5709:19d03] datacellR2C2 as text --> 123,456,789 <---
2012-07-07 22:16:15.916 [5709:19d03] originalValue2 = 123.000000 <--
只需用一个简单的 删除它们+stringByReplacingOccurrencesOfString:withString:
,并删除那些尾随逗号:
//test
NSString *string = @"123,456,789";
NSString *cleanString = [string stringByReplacingOccurrencesOfString:@"," withString:@""];
float originalValue2 = [cleanString floatValue];
NSLog(@"datacellR2C2 as text --> %@ <---\n",cleanString); // this correctly shows the value in datacellR2C2
NSLog(@"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:20:20.737 [5887:19d03] datacellR2C2 as text --> 123456789 <---
2012-07-07 22:20:20.739 [5887:19d03] originalValue2 = 123456792.000000 <--
顺便说一句,浮点数将该字符串四舍五入为偶数,请改用双精度。