3

Let's say I have an NSNumber object that holds a value 0.12345. All I want is an NSNumber object with a same value, but rounded to a specified number of significant digits, say 2, so value looks like this: 0.12.

  • I don't want to convert it to NSString and back, which is what some of the answers suggest
  • I would prefer not to cast/convert and/or do multiplication/division manually like in this answer

Is there an obvious way to do it that I am missing?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
C0D3LIC1OU5
  • 8,600
  • 2
  • 37
  • 47
  • 1
    `NSNumber` doesn't have any built-in rounding functions. You could use `NSDecimalNumber` which does. – dan Aug 15 '17 at 21:08
  • 3
    Explain your goal a bit more. Why do you need to round the `NSNumber`? – rmaddy Aug 15 '17 at 21:27
  • 2
    "I would prefer not to ..." - explain why you don't want to solve a math problem with math. There are plenty of answers in your linked question, ranging from bad to good (the scores will help with that). – CRD Aug 16 '17 at 08:13

2 Answers2

3

It's pretty much impossible to do it and maintain all your constraints. NSNumber has no rounding methods, so you're going to have to convert to something else. The obvious route is to convert to a double and multiply, round and divide, but you say you would prefer not to do that. So that leaves this route:

NSNumber *round(NSNumber *number, NSInteger places, NSRoundingMode mode) {
    NSDecimal d = number.decimalValue;
    NSDecimal rd;
    NSDecimalRound(&rd, &d, places, mode);
    return [NSDecimalNumber decimalNumberWithDecimal:rd];
}
idz
  • 12,825
  • 1
  • 29
  • 40
-1

Another hacky way is:

  1. Convert your number to round after multiplied it by 100.

int yourNum = 0.12345 * 100; yourNum now is 12.

  1. Then whenever you need the number just divide by 100.

float yourNumF = yourNum / 100.0;

Not a fan of this method myself but it fits your requirement. :D

GeneCode
  • 7,545
  • 8
  • 50
  • 85