0

我在 xib 文件中有一个文本字段。在 .m 文件中的一个方法中,我可以打印文本字段的内容,但我无法将这些内容转换为浮点数。文本字段用逗号格式化,如 123,456,789。下面是代码片段,其中 datacellR2C2 是文本字段。

float originalValue2 = originalValue2 = [datacellR2C2.text  floatValue];
NSLog(@"datacellR2C2 as text --> %@ <---\n",datacellR2C2.text);  // this correctly shows the value in datacellR2C2
NSLog(@"originalValue2 = %f  <--\n", originalValue2);  // this incorrectly returns the value 1.0 

我将不胜感激任何关于修复或我应该寻找问题的方向的建议。

4

1 回答 1

1

-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  <--

顺便说一句,浮点数将该字符串四舍五入为偶数,请改用双精度。

于 2012-07-08T03:20:59.063 回答