开发者

NSNumber Formatting (Round to 1000's place)

I currently have a series of NSNumber objects with values between 0 and 500,000. They are randomly generated values with many dec开发者_高级运维imal places.

How can I print these values, but round them to the nearest 1000? For example 32143.8472 would round to 32000. For simplicity, lets assume I want them in a NSLog...

eg.

NSLog(@"The number is: %@", WHATGOESHERE??)


NSNumber objects are suitable for storing values, for numeric operations you should use plain numeric types (e.g. int)

Try the following code:

int rounded = 1000*(([number intValue]+500)/1000);

What happens there:

  1. [number intValue]
    That gets integer part of our number

  2. add 500 and divide by 1000 - get the nearest number of thousands in our number

  3. Multiply by 1000 - compensate for previous division to get a number actually rounded to the thousands

And log it if you want:

NSLog(@"The number is: %d", rounded)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜