0

I would to round a decimal number like this :

4363,65 ----> 4364

I have tried this :

NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString@"4363,65"];

NSDecimalNumberHandler  *behav = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain scale:NSDecimalNoScale
                                                raiseOnExactness:YES
                                                 raiseOnOverflow:YES
                                                raiseOnUnderflow:YES
                                             raiseOnDivideByZero:YES];

NSDecimalNumber *roundedDecimal = [decimalNumber decimalNumberByRoundingAccordingToBehavior:behav];

I don't have the expected result.How i can round it ?

samir
  • 4,501
  • 6
  • 49
  • 76

2 Answers2

1

I see 2 problems in your code. The first is the creation of the number. You are using , as a decimal separator. If your locale is not configured to use , for decimals, your number will be parsed as 4363. This is what probably happens.

The second problem is the value for the scale parameter. It takes the number of decimal digits but you are using a constant NSDecimalNoScale which is actually equal to SHRT_MAX. That's not what you want.

//make sure you use the correct format depending on your locale
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:@"4363.65"]; 

NSDecimalNumberHandler  *behav = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain
                                                       scale:0
                                            raiseOnExactness:YES
                                             raiseOnOverflow:YES
                                            raiseOnUnderflow:YES
                                         raiseOnDivideByZero:YES];
Sulthan
  • 128,090
  • 22
  • 218
  • 270
-1

This is the easiest way: float f = 4363,65; int rounded = (f + 0.5);

agy
  • 2,804
  • 2
  • 15
  • 22