NSString *longtempstring = [tmp description];
What is the value of longtempstring
here? Is it even a number?
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:3];
[formatter setMinimumFractionDigits:0];
Why do you set maximum fraction digits to 3
if you say that you don't want any fraction digits? Fraction digits are what is "after the dot" and you say you don't want any decimals. If you don't want any decimals, minimum and maximum must be set to 0
.
NSString *shorttempstring = [formatter stringForObjectValue:[NSString stringWithString:longtempstring]];
First of all, why are you copying the string? [NSString stringWithString:...]
creates a new string that is a copy of the string you provide as argument. Strings are immutable, there is no need to copy them, they won't be modified. If you are afraid that a NSString
may in fact be a NSMutableString
, after all that is a subclass of NSString
and you want to copy it, just copy it by calling [aString copy]
. copy
is a very smart method here. If the NSString
is in fact a mutable string, it will really copy it, so you get an immutable copy. If it is not a mutable string, though, copy
just returns the same string with a retain count increased by one (so in that case copy
behaves exactly like retain
). However, in your case copying makes no sense whatsoever.
And second, what makes you believe, that you can feed a string into a NSNumberFormater
? It is called NSNumberFormater
because it formats objects of type NSNumber
. How is a NSString
a NSNumber
? It is not called NSStringFormater
. If you feed an object of the wrong class to a formater, it will return nil
, that's how this method is documented.
If your longtempstring
contains a number with fraction, e.g. 12.345
, then the correct code would look like this:
NSString * longtempstring = [tmp description];
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
[formatter setMinimumFractionDigits:0];
NSNumber * tempnumber = [NSNumber numberWithDouble:[longtempstring doubleValue]];
NSString * shorttempstring = [formatter stringForObjectValue:tempnumber];
However, if all you want to do is cut off the decimals, that is a horrible way to do it. This can be done much more effective:
double d;
NSString * longtempstring;
NSString * shorttempstring;
longtempstring = @"12.345";
d = [longtempstring doubleValue];
shorttempstring = [NSString stringWithFormat:@"%d", (int)d];
This is much shorter, needs less memory, and is at least three times faster. If you want to round the number (that means everything with a fraction .5
and above is rounded to the next higher value), just round it:
d = round([longtempstring doubleValue]);