Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a NSDecimalnumber between decimal & integer & back

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...

like image 291
mamcx Avatar asked Jan 28 '09 16:01

mamcx


1 Answers

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.

like image 166
Ashley Clark Avatar answered Oct 09 '22 17:10

Ashley Clark