Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exponent of NSDecimalNumber in Objective-C?

Given an NSDecimalNumber, how can I find the exponent (scale)?

Although it should in principle be possible to do this by first converting to an NSString followed by some ugly string manipulation, I'd rather avoid it.

With a Java BigDecimal, I can call the scale() method to get the scale.

Does a similarly concise method exist for NSDecimalNumber?

like image 770
Rich Apodaca Avatar asked Sep 28 '12 15:09

Rich Apodaca


1 Answers

If you really need the exponent for some reason (other than simply display, which you can configure a number formatter to give you), you can get the primitive double with the -doubleValue method and then use frexp(3) to get the mantissa and exponent values.

The whole design behind objects for doing and storing floating point math is that you can handle computational and precision errors more effectively, however, the limitation of that design is once you convert from a scalar (such as a double or the combination of a mantissa and exponent), you are expected to stay within the object framework and not convert back to a (potentially) less precise format.

I suggest using the -doubleValue is the best option, since other answers suggest accessing private structure records which may change, and using these suggests no precision loss, when, in fact, there very well may be (as documented in the header files). When converting to a double, you and those who use/read your code know exactly what precision errors may be possible because the type is very well understood and very well documented.

Finally, if you want to be sure if a conversion is going to cause an error, you can create and use an NSDecimalNumberHandler which will give you information about what kind of rounding/precision errors you can expect when converting to the double scalar type.

I also suggest you add an enhancement request using the apple bug reporter stating that you'd like access to the exponent directly as well as possibly adding a higher precision type, like a -longDoubleValue method.

Edit includes more information

like image 104
Jason Coco Avatar answered Sep 29 '22 15:09

Jason Coco