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.
Objective C, Trim a float
540 views Asked by Dan Paschevici At
4
There are 4 answers
0
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.length
because 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
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);
You can use NSNumberFormatter
Or simply
If you want only last four digits, convert the float to a string
and get the last four characters