需要编写一个函数,将字符串转换为double而不调用任何内置实用程序,例如atof()
,Double.parseDouble()
,Double.valueOf()
,[NSString doubleValue]
,{ {1}},[NSScanner scanDouble]
或任何类似的方法。
答案 0 :(得分:3)
const char *s = "-123.456";
int sign = 1;
int hasdp = 0;
int dplaces = 0;
float f = 0.0;
while(*s) {
switch (*s) {
case '-': sign = -1; break;
case '.': hasdp = 1; break;
default:
f *= 10;
f += *s - '0';
break;
}
s++;
if (hasdp) dplaces++;
}
f *= sign;
int i;
for (i = 1; i < dplaces; i++) f /= 10;
// we need to start from 1 in order to get
// the correct result, this is a property
// of this algorithm
现在f
将包含已解析的值,前提是其格式正确(可选 - 前缀,可选小数点后跟1个或多个小数位。
答案 1 :(得分:2)
尝试以下方法:
- (void)myMethod:(NSString *)numberString{
int i = 0;
float number = 0.0;
while ([numberString length] > i) {
NSString *myChar = [numberString substringWithRange:NSMakeRange(i, 1)];
NSLog(@"%@", [numberString substringWithRange:NSMakeRange(i, 1)]);
i++;
if ([myChar isEqualToString:@"1"]){
number = number * 10 + 1;
} else if ([myChar isEqualToString:@"2"]){
number = number * 10 + 2;
} else if ([myChar isEqualToString:@"3"]){
number = number * 10 + 3;
} else if ([myChar isEqualToString:@"4"]){
number = number * 10 + 4;
} else if ([myChar isEqualToString:@"5"]){
number = number * 10 + 5;
} else if ([myChar isEqualToString:@"6"]){
number = number * 10 + 6;
} else if ([myChar isEqualToString:@"7"]){
number = number * 10 + 7;
} else if ([myChar isEqualToString:@"8"]){
number = number * 10 + 8;
} else if ([myChar isEqualToString:@"9"]){
number = number * 10 + 9;
} else if ([myChar isEqualToString:@"0"]){
number = number * 10 + 0;
}
}
}