Round doubles in Objective-C

前端 未结 4 2014
长情又很酷
长情又很酷 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

    You can print it to 3 decimal places with [NSString stringWithFormat:@"%.3f",d].

    You can approximately round it with round(d*1000)/1000, but of course this isn't guaranteed to be exact since 1000 isn't a power of 2.

提交回复
热议问题