Round doubles in Objective-C

前端 未结 4 2019
长情又很酷
长情又很酷 2021-01-17 16:28

I have double number in a format like 34.123456789. How can I change it to 34.123?

I just want 3 digits after the decimal point.

4条回答
  •  感情败类
    2021-01-17 17:20

    If you want to make

    34.123456789 -> 34.123
    34.000000000 -> 34 not 34.000
    

    You can use NSNumberFormatter

    NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
    [fmt setMaximumFractionDigits:3]; // 3 is the number of digits
    
    NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:34.123456789]]);  // print 34.123
    NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:34.000000000]]);  // print 34
    

提交回复
热议问题