Search code examples
iosnsnumber

Objective C, Trim a float


I have float like 3500,435232123. All I want to know if exists (in Objective C) a function that let me keep just the last 4 digits in my case is 2123.


Solution

  • You can use NSNumberFormatter

    NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
    [format setNumberStyle:NSNumberFormatterDecimalStyle];
    [format setRoundingMode:NSNumberFormatterRoundHalfUp];
    [format setMaximumFractionDigits:4];
    [format setMinimumFractionDigits:4];
    
    string = [NSString stringWithFormat:@"%@",[format stringFromNumber:[NSNumber numberWithFloat:65.50055]] ;
    

    Or simply

    NSString *string = [NSString stringWithFormat:@"%.04f", floatValue];
    

    If you want only last four digits, convert the float to a string

    NSString *string = [NSString stringWithFormat:@"%f", floatValue];
    

    and get the last four characters

    NSString *lastFour = [string substringFromIndex: [string length] - 4];