How to split NSDecimalnumber between decimal & integer & back

I cannot figure out how to get the integral and decimal value from NSDecimalnumber.

For example, if I have 10.5, how to get 10 and 5?

And if I have 10 and 5, how do I get back to 10.5?


Mmm ok, it looks better!

However, I do have a decimal loss agreement.

This is an application that will be international. If, for example, the user sets the price to "124.2356", I want to download and save the exact number.


Mmm ok, so, but do not follow # decimals. If there is a way to find out which of the current local I am installed.

This is because it represents currency values โ€‹โ€‹...

+7
math objective-c cocoa nsdecimalnumber
source share
4 answers

I use 2 for the scale, since you said it was for the currency, but you can use a different rounding scale. I also ignore any exceptions that might be rounded as 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]; 

This will give you 10 and 0.5 in the variables dollars and cents , respectively. If you want to use integers, you can use this method to multiply your cents by a power of 10.

 cents = [cents decimalNumberByMultiplyingByPowerOf10: 2]; 

Which, in turn, will multiply you by cents by 100, giving you 10 and 5 in dollars and cents . You should also know that here you can use the negative powers of 10 here.

So,

 cents = [cents decimalNumberByMultiplyingByPowerOf10: -2]; 

cancels the last method.

+19
source share

Not sure which functions of the Math c lens have, but something like

 Math.floor(10.5) = 10 (10.5 - 10) * 10 = 5 

bit of a clearer example (cos 10)

 Math.floor(20.4) = 20 (20.4 - 20) * 10 = 4; 

Another problem

 (5 / 10) = .5 10 + .5 = 10.5 

10 used in decimal points depends on the number of decimal places ... e.g.

 Math.floor(20.44) = 20 (20.44 - 20) * 100 = 44; 

time is required for 100

0
source share

If you don't have access to fns math, this might work:

 double val = [dn doubleValue]; // dn is a NSDecimalNumber* int intPart = (int) val; double doublePart = (val - intPart); 

This may give you some problems, the cycle can never end, in which case you will need to set a counter:

 while (doublePart != (int)doublePart) doublePart*=10; 
0
source share

double floor (double x); is a POSIX function. This function can be used to find the highest integer value of at most x .

 double x = 10.5; double y = floor (x); // y = 10.0 double z = x - y; // z = 0.5 
-one
source share

All Articles