• iOS返回一个前面没有0,小数点后保留两位的数字字符串


    /*
     * 处理一个数字加小数点的字符串,前面无0,保留两位。网上有循环截取的方法,如果数字过长,浪费内存,这个方法在优化内存的基础上设计的。
     */
    -(NSString*)getTheCorrectNum:(NSString*)tempString
    {
        //先判断第一位是不是 . ,是 . 补0
        if ([tempString hasPrefix:@"."]) {
            tempString = [NSString stringWithFormat:@"0%@",tempString];
        }
        //计算截取的长度
        NSUInteger endLength = tempString.length;
        //判断字符串是否包含 .
        if ([tempString containsString:@"."]) {
            //取得 . 的位置
            NSRange pointRange = [tempString rangeOfString:@"."];
            NSLog(@"%lu",pointRange.location);
            //判断 . 后面有几位
            NSUInteger f = tempString.length - 1 - pointRange.location;
            //如果大于2位就截取字符串保留两位,如果小于两位,直接截取
            if (f > 2) {
                endLength = pointRange.location + 2;
            }
        }
        //先将tempString转换成char型数组
        NSUInteger start = 0;
        const char *tempChar = [tempString UTF8String];
        //遍历,去除取得第一位不是0的位置
        for (int i = 0; i < tempString.length; i++) {
            if (tempChar[i] == '0') {
                start++;
            }else {
                break;
            }
        }
        //如果第一个字母为 . start后退一位
        if (tempChar[start] == '.') {
            start--;
        }
        //根据最终的开始位置,计算长度,并截取
        NSRange range = {start,endLength-start};
        tempString = [tempString substringWithRange:range];
        return tempString;
    }
  • 相关阅读:
    hdu 4739 Zhuge Liang's Mines DFS
    Uva 12304
    三角形的心
    最小路径覆盖的理解
    Codeforces Round #192 (Div. 2)
    Uva 11796 Dog Distance
    laravel框架session使用教程
    php session跨页面传递 session值丢失问题
    PHP 5.4中的traits特性
    PHP5.3 goto操作符介绍
  • 原文地址:https://www.cnblogs.com/beijingxiaoguo/p/4424228.html
Copyright © 2020-2023  润新知