zoukankan      html  css  js  c++  java
  • iOS 当请求到的数据是double类型,会失去精准度,并且去掉小数点后的0

    首先请求到的数据都会变成字符串,先将字符串转化为double类型

    double fdouble = [str doubleValue];

    然后再设置小数点后的位数

    [NSString stringWithFormat:@"%.1f", fdouble];

     重点:  提供一个NSSing的扩展,传入需要保留的小数位,返回字符串。并且去掉末尾的0.

    #import <Foundation/Foundation.h>
    
    @interface NSString (EliminateZero)
    
    //   integer  必传
    - (NSString *)eliminateZeroWithDouble:(NSInteger)integer;
    
    @end
    
    
    
    #import "NSString+EliminateZero.h"
    
    @implementation NSString (EliminateZero)
    
    - (NSString *)eliminateZeroWithDouble:(NSInteger)integer{
        
        NSString *str = [self copy];
        
        double fdouble = [str doubleValue];
        
        NSString *ftotal;
        switch (integer) {
            case 1:
                ftotal = [NSString stringWithFormat:@"%.1f", fdouble];
                break;
            case 2:
                ftotal = [NSString stringWithFormat:@"%.2f", fdouble];
                break;
            case 3:
                ftotal = [NSString stringWithFormat:@"%.3f", fdouble];
                break;
            case 4:
                ftotal = [NSString stringWithFormat:@"%.4f", fdouble];
                break;
            case 5:
                ftotal = [NSString stringWithFormat:@"%.5f", fdouble];
                break;
            default:
                break;
        }
    
        while ([ftotal hasSuffix:@"0"]) {
            ftotal = [ftotal substringToIndex:[ftotal length]-1];
        }
        
        if ([ftotal hasSuffix:@"."]) {
            ftotal = [ftotal substringToIndex:[ftotal length]-1];
        }
        
        return ftotal;
        
    }
    
    
    @end

     

     

     

  • 相关阅读:
    334 Increasing Triplet Subsequence 递增的三元子序列
    332 Reconstruct Itinerary 重建行程单
    331 Verify Preorder Serialization of a Binary Tree 验证二叉树的前序序列化
    330 Patching Array
    329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径
    328 Odd Even Linked List 奇偶链表
    327 Count of Range Sum 区间和计数
    326 Power of Three 3的幂
    Java中的Class.forName
    巧用Java中Calendar工具类
  • 原文地址:https://www.cnblogs.com/weipeng168/p/6203531.html
Copyright © 2011-2022 走看看