Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber Formatting (Round to 1000's place)

Tags:

objective-c

I currently have a series of NSNumber objects with values between 0 and 500,000. They are randomly generated values with many decimal 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??)
like image 588
Matt Helm Avatar asked Dec 10 '25 10:12

Matt Helm


1 Answers

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)
like image 97
Vladimir Avatar answered Dec 11 '25 22:12

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!