将 NSString 转换为浮点数 - Objective C
Convert NSString to float - Objective C
我想将一个字符串转换为浮点数,这里是我写的代码:
NSString *latString = [[response valueForKey:@"coords"] valueForKey:@"lat"];
NSLog(@"Latitude String: %@", latString);
self.coordLat = [latString floatValue];
NSLog(@"Latitude: %lu", (unsigned long) self.coordLat);
但这是我得到的:
2016-03-14 17:36:00.471 marsad[9968:186761] Latitude String: 36.860532
2016-03-14 17:36:00.587 marsad[9852:152630] Latitude: 36
unsigned long
类型类似于 integers
所以小数点自然会被截断。
试试 NSLog(@"Latitude: %f", self.coordLat);
。
NSLog(@"Latitude: %lu", (unsigned long) self.coordLat);
这会将值转换为长整型。
你应该使用类似的东西:
NSLog(@"Latitude: %f", self.coordLat);
您可以使用 NSString
floatValue
只读 属性,如 Apple docs 中所述:
This property doesn’t include whitespace at the beginning of the string. This property is HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow. This property is 0.0 if the string doesn’t begin with a valid text representation of a floating-point number.
如果您的字符串格式正确,您可以使用 :
将其转换为浮点数
NSString *val = @"3.45";
float fCost = [val floatValue];
NSLog(@"Latitude: %g", self.coordLat);
64 位浮点数(双精度),如果指数小于 –4 或大于或等于精度,则以 %e 的样式打印,否则以 %f 的样式打印。
我想将一个字符串转换为浮点数,这里是我写的代码:
NSString *latString = [[response valueForKey:@"coords"] valueForKey:@"lat"];
NSLog(@"Latitude String: %@", latString);
self.coordLat = [latString floatValue];
NSLog(@"Latitude: %lu", (unsigned long) self.coordLat);
但这是我得到的:
2016-03-14 17:36:00.471 marsad[9968:186761] Latitude String: 36.860532
2016-03-14 17:36:00.587 marsad[9852:152630] Latitude: 36
unsigned long
类型类似于 integers
所以小数点自然会被截断。
试试 NSLog(@"Latitude: %f", self.coordLat);
。
NSLog(@"Latitude: %lu", (unsigned long) self.coordLat);
这会将值转换为长整型。 你应该使用类似的东西:
NSLog(@"Latitude: %f", self.coordLat);
您可以使用 NSString
floatValue
只读 属性,如 Apple docs 中所述:
This property doesn’t include whitespace at the beginning of the string. This property is HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow. This property is 0.0 if the string doesn’t begin with a valid text representation of a floating-point number.
如果您的字符串格式正确,您可以使用 :
将其转换为浮点数NSString *val = @"3.45";
float fCost = [val floatValue];
NSLog(@"Latitude: %g", self.coordLat);
64 位浮点数(双精度),如果指数小于 –4 或大于或等于精度,则以 %e 的样式打印,否则以 %f 的样式打印。