Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round NSNumber to a specific number of significant digits

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?

like image 668
C0D3LIC1OU5 Avatar asked Jan 01 '26 17:01

C0D3LIC1OU5


1 Answers

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];
}
like image 97
idz Avatar answered Jan 03 '26 15:01

idz



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!