2012-07-08 66 views
0

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

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 

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

+0

为什么你有浮动originalValue2 = originalValue2 = ....;?而不是originalValue2 = .....; – tarheel 2012-07-08 03:16:39

+0

这是我发布的文本中的拼写错误。我仔细检查过,它不在原文中。对不起,可能造成的任何混淆。原来是... float originalValue2 = [datacellR2C2.text floatValue]; – K17 2012-07-08 03:18:07

回答

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

顺便说一句,一个浮子舍入字符串,最多为偶数,则使用双精度而不是。

+0

哎呀...我不敢相信我写了'doubleValue' ... – CodaFi 2012-07-08 03:28:44

+0

谢谢!!!!!!! – K17 2012-07-08 04:04:38