How to trim zeros after decimal point

后端 未结 8 1665
栀梦
栀梦 2021-01-05 05:38

I am trying to trim zeros after a decimal point as below but it\'s not giving desired result.

trig = [currentVal doubleValue];
trig = trig/100;
NSNumberForma         


        
8条回答
  •  时光说笑
    2021-01-05 06:06

    This may not be a proper solution where there is NSNumberFormetter Class, But I just did this rather then googling a lot! ;)

    Here is an example, if it helps:

    -(NSString*) trimZerosAfterDecimalPoint:(NSString*)string_ {
    
        double doubleValue=[string_ doubleValue];    
        long   leftPart=(long)doubleValue;
        double rightPart=doubleValue-(double)leftPart;
    
        NSString *rightPartAsStr=[NSString stringWithFormat:@"%f", rightPart];
    
        int i=0;
        for (i=rightPartAsStr.length-1; i>=2; i--) {
            if ([rightPartAsStr characterAtIndex:i]!='0') {            
                rightPartAsStr=[rightPartAsStr substringWithRange:NSMakeRange(2, i-1)];
                break;
            }
        }
    
        if (i<2) {
            string_=[NSString stringWithFormat:@"%ld", leftPart];
        } else {
            string_=[NSString stringWithFormat:@"%ld.%@", leftPart, rightPartAsStr];
        }
    
        return string_;
    }
    

提交回复
热议问题