I can't figure how get the integral & decimal value from a NSDecimalnumber.
For example, if I have 10,5, how get 10 & 5?
And if I have 10 & 5, how return to 10,5?
Mmm ok, that is looking better!
However I have the concer about lossing decimals.
This is for a app that will be international. If for example a user set the price "124,2356" I wanna load & save the exact number.
Mmm ok, that is the way, but not respect the # of decimal places. If exist a way to know that from the current local I'm set.
This is because that represent currency values...
I'm using 2 for the scale since you said this was for currency but you may choose to use another rounding scale. I'm also ignoring any exceptions rounding may bring since this is a pretty simple example.
NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:0 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *price = /* eg. 10.5 */;
NSDecimalNumber *dollars = [price decimalNumberByRoundingAccordingToBehavior: behavior];
NSDecimalNumber *cents = [price decimalNumberBySubtracting: dollars];
That will give you 10 and 0.5 in the dollars
and cents
variables respectively. If you want whole numbers you can use this method to multiply your cents
by a power of 10.
cents = [cents decimalNumberByMultiplyingByPowerOf10: 2];
Which will in turn multiply you cents
by 100, giving you 10 and 5 in dollars
and cents
. You should also know that you can use negative powers of 10 here to divide.
So,
cents = [cents decimalNumberByMultiplyingByPowerOf10: -2];
would undo that last method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With