0

I am dealing with generating reports with values that are sometimes integral, sometimes 1 decimal and sometimes 2 decimals. I would like to find a way to display these numbers with as few decimal points as possible. So 1 would always be 1 and not 1.0 or 1.00 whereas 2.5743 would be 2.57. Is there a way to automatically doing this slash something helpful in an iOS SDK that takes care of this?

helloB
  • 3,472
  • 10
  • 40
  • 87
  • As far as I know, there isn't some "remove all trailing zeros" property that you can use. I would suggest using `NSRange` and the `NSString .length` property with a couple if statements to check if the last digit is "0". – MSU_Bulldog Feb 04 '16 at 19:36

1 Answers1

0

Use an NSNumberFormatter with maximumFractionDigits set to 2.

@import Foundation;

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.maximumFractionDigits = 2;
        NSLog(@"%@", [formatter stringFromNumber:@(1)]);
        NSLog(@"%@", [formatter stringFromNumber:@(1.0)]);
        NSLog(@"%@", [formatter stringFromNumber:@(2.5743)]);
        NSLog(@"%@", [formatter stringFromNumber:@(2.5)]);
        NSLog(@"%@", [formatter stringFromNumber:@(2.7)]);
        NSLog(@"%@", [formatter stringFromNumber:@(2.699)]);
        NSLog(@"%@", [formatter stringFromNumber:@(2.71001)]);
    }
    return 0;
}

Output:

2016-02-04 13:46:36.002 commandLine[27474:1266926] 1
2016-02-04 13:46:36.002 commandLine[27474:1266926] 1
2016-02-04 13:46:36.003 commandLine[27474:1266926] 2.57
2016-02-04 13:46:36.003 commandLine[27474:1266926] 2.5
2016-02-04 13:46:36.003 commandLine[27474:1266926] 2.7
2016-02-04 13:46:36.003 commandLine[27474:1266926] 2.7
2016-02-04 13:46:36.003 commandLine[27474:1266926] 2.71
rob mayoff
  • 375,296
  • 67
  • 796
  • 848