iOS返回一個前面沒有0,小數點後保留兩位的數字字串,ios小數點

來源:互聯網
上載者:User

iOS返回一個前面沒有0,小數點後保留兩位的數字字串,ios小數點

/* * 處理一個數字加小數點的字串,前面無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;}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.