How do I change the number of decimal places iOS?

前端 未结 5 1309
抹茶落季
抹茶落季 2020-12-10 21:04

I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don\'t want i

5条回答
  •  余生分开走
    2020-12-10 21:30

    I had the same problem. This is the code snippet that solved it (looks a lot like Caleb's solution, but that one didn't work for me, so I had to add an extra line):

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = kCFNumberFormatterDecimalStyle;
    numberFormatter.maximumFractionDigits = 20;
    numberFormatter.minimumFractionDigits = 0;
    
    NSNumber *number = [[NSNumber alloc]init];
    NSString *numberString = [numberFormatter stringFromNumber:number];
    

    We can use another numberStyle and override its basic appearance, setting desired properties of an NSNumberFormatter.

提交回复
热议问题