Adopted by: NSDecimalNumberHandler
Declared in: Foundation/NSDecimalNumber.h
The NSDecimalBehaviors protocol declares three methods that control the discretionary aspects of working with NSDecimalNumbers. The scale and roundingMode methods determine the precision of NSDecimalNumber's return values, and the way in which those values should be rounded to fit that precision. The exceptionDuringOperation:error:leftOperand:rightOperand: method determines the way in which an NSDecimalNumber should handle different calculation errors.
For an example of a class that adopts the NSDecimalBehaviors protocol, see the specification for NSDecimalNumberHandler.
- Rounding
- - roundingMode
- - scale
- Handling errors
- - exceptionDuringOperation:error:leftOperand:rightOperand:
- (NSDecimalNumber *)exceptionDuringOperation:(SEL)method
error:(NSCalculationError)error
leftOperand:(NSDecimalNumber *)leftOperand
rightOperand:(NSDecimalNumber *)rightOperand
There are four possible values for error. The first three have to do with limits on NSDecimalNumber's ability to represent decimal numbers. An NSDecimalNumber can represent any number that can be expressed as mantissa x 10^exponent, where mantissa is a decimal integer up to 38 digits long, and exponent is between -256 and 256. If these limits are exceeded, the NSDecimalNumber returns one of the following errors:
The last error is simpler:
In implementing exceptionDuringOperation:error:leftOperand:rightOperand:, you can handle each of these errors in several ways:
- (NSRoundingMode)roundingMode
The rounding mode only matters if the scale method sets a limit on the precision of NSDecimalNumber return values. It has no effect if scale returns NSDecimalNoScale.
Assuming that scale returns 1, the NSRoundingMode has the following effects on various original values:
Original value | NSRoundDown | NSRoundUp | NSRoundPlain | NSRoundBankers |
1.24 | 1.2 | 1.3 | 1.2 | 1.2 |
1.26 | 1.2 | 1.3 | 1.3 | 1.3 |
1.25 | 1.2 | 1.3 | 1.3 | 1.2 |
1.35 | 1.3 | 1.4 | 1.4 | 1.4 |
-1.35 | -1.4 | -1.3 | -1.4 | -1.4 |
- (short)scale
Specifically, scale returns the number of digits allowed after the decimal separator. If scale returns a negative value, it affects the digits before the decimal separator as well. If scale returns NSDecimalNoScale, the number of digits is unlimited.
Assuming that roundingMode returns NSRoundPlain, different values of scale have the following effects on the number 123.456:
Scale | Return value |
NSDecimalNoScale | 123.456 |
2 | 123.45 |
0 | 123 |
-2 | 100 |