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:
[number intValue]
That gets integer part of our numberadd 500 and divide by 1000 - get the nearest number of thousands in our number
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)
精彩评论