ios保留四个小数位

+ (NSString*) decimalNumberWithDouble4:(double)value

{

    value = round(value*10000)/10000;


    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    [numberFormatter setPositiveFormat:@"0.0000"];

    NSString *string = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]];


    if ([string hasSuffix:@".0000"])  {

        string = [string substringToIndex:string.length - 5];

    } else if ([string hasSuffix:@".000"])  {

        string = [string substringToIndex:string.length - 4];

    } else if ([string hasSuffix:@".00"]) {

        string = [string substringToIndex:string.length - 3];

    } else if ([string hasSuffix:@".0"]) {

        string = [string substringToIndex:string.length - 2];

    }


    if ([string containsString:@"."]) {

        if ([string hasSuffix:@"0000"]) {

            string = [string substringToIndex:string.length - 4];

        } else if ([string hasSuffix:@"000"]) {

            string = [string substringToIndex:string.length - 3];

        } else if ([string hasSuffix:@"00"]) {

            string = [string substringToIndex:string.length - 2];

        } else if ([string hasSuffix:@"0"]) {

            string = [string substringToIndex:string.length - 1];

        }

    }


    return string;

}

你可能感兴趣的:(ios保留四个小数位)