The easiest way is to probably roll your own. I've had to do this in C before since there's no way to get the behavior you want with printf
formatting.
It doesn't appear to be much easier in Objective-C either. I'd give this a try:
NSString *ftotal = [NSString stringWithFormat: @"%.2f", total];
while ([ftotal hasSuffix:@"0"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}
if ([ftotal hasSuffix:@"."]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}
or this (possibly faster) variant:
NSString *ftotal = [NSString stringWithFormat: @"%.2f", total];
if ([ftotal hasSuffix:@".00"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-3];
} else {
if ([ftotal hasSuffix:@"0"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}
}
The stringWithFormat
guarantees there will always be a ".nn"
at the end (where n
is a digit character). The while
and if
simply strip off trailing zeros and the trailing decimal if it was an integer.
Obviously, you may want to put it in a function or class so you can get at it from anywhere without having to duplicate the code all over the place.