欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

可能会用到

程序员文章站 2024-02-21 17:09:04
...

输入的字符串转换为数字

- (float)Transform:(NSMutableString *)str {
    int flag = 0, zhen = 1;
    float sum = 0, temp = 0, t = 0.0;
    if ([str characterAtIndex:0] == '-') {
        zhen = 0;
    } else {
        temp = (int)[str characterAtIndex:0] - 48;
    }
    if ([str length] > 1) {
        for (int i = 1; i < [str length]; i++) {
            if ([str characterAtIndex:i] == '.') {
                sum += temp;
                temp = 0.1 * ((int)[str characterAtIndex:++i] - 48);
                t = 0.01;
                flag = 1;
                continue;
            } else {
                if (flag == 0) {
                    temp = temp * 10 + (int)[str characterAtIndex:i] - 48;
                } else {
                    temp = temp + t * ((int)[str characterAtIndex:i] - 48);
                    t = 0.1 * t;
                }
            }
        }
        sum += temp;
    } else {
        sum = (int)[str characterAtIndex:0] - 48;
    }
    if (zhen == 0) {
        return sum * (-1);
    } else {
        return sum;
    }
}