Objective C, Trim a float

540 views Asked by At

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.

4

There are 4 answers

1
Fawad Masud On BEST ANSWER

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];
0
agy On

It you want to get the decimal part, you can do x - floor(x). For instance:

float x = 3500,435232123;
NSString *string = [NSString stringWithFormat:@"%.04f", x - floor(x)];

And to get 4 decimal digits do what Fawad Masud says.

0
Fabio Berger On

No there is no such function, as far as i know. But here is a way to achieve exactly what you want.

First you have to round it to four digits after point:

NSString *exampleString = [NSString stringWithFormat:@"%.04f", valueToRound];

Then you get the location for the comma inside the exampleString:

NSRange commaRange = [valueString rangeOfString:@","];

Finally you create the finalString with the values from that NSRange. The substring starts at commaRange.location+commaRange.lengthbecause thats the index directly after the comma.

NSString *finalString = [valueString substringWithRange:NSMakeRange(commaRange.location+commaRange.length,valueString.length-commaRange.location-commaRange.length)];

Hope that helps you.

0
0yeoj On

I think is no predefined function for that.

and the solution i thought of is:

float floatNum = 3500.435232123;

converting float number to string and trim/substring the string, like for example:

NSString *stringFloat = [NSString stringWithFormat:@"%f", floatNum];
NSString *newString = [stringFloat substringWithRange:NSMakeRange(stringFloat.length - 4, stringFloat.length)];

NSLog(@"%@", newString);

another is something like:

NSString *stringFloat = [NSString stringWithFormat:@"%f", floatNum];

//separates the floating number to 
arr[0] = whole number
arr[1] = decimals

NSArray *arr=[str componentsSeparatedByString:@"."];

since you just want to work on the decimal, i think arr[1] is what you need..

NSString *stringDecimals = (NSString *)arr[1];

if ( stringDecimals.length > 4) //check the length of the decimals then cut if exceeds 4 character..
{
    stringDecimals = [stringDecimals substringWithRange:NSMakeRange(stringDecimals.length - 4, stringDecimals.length)];
}

NSLog(@"stringDecimals: %@", stringDecimals);