0

How rounded decimal 2?

48382,06 + 86106,62 + 83650,07 + 72939,61 = 291078,36

NSNumber *returnSum = 0;

for (int i = 0; i < [arraySum count]; i++) {
        PayDoc *payDoc = (PayDoc*)([arraySum objectAtIndex:i]);
        returnSum = [NSNumber numberWithFloat:[returnSum floatValue]+[payDoc.SOBTR floatValue]];
    }

Answer result my code returnSum = 291078,38

Valeriy
  • 723
  • 6
  • 17

4 Answers4

3

Use NSDecimalNumber. Set scale to 2 and roundingMode to NSRoundPlain

NSDecimalNumber *returnSum = [[NSDecimalNumber alloc] initWithFloat:0.0f];

for (PayDoc *payDoc in arraySum) {

        NSDecimalNumber *sobtr = [[NSDecimalNumber alloc] initWithFloat:payDoc.SOBTR.floatValue];
        returnSum = [returnSum decimalNumberByAdding:sobtr withBehavior:[NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:YES raiseOnOverflow:YES raiseOnUnderflow:YES raiseOnDivideByZero:YES]];
}

I tested the above values and it gives 291078.36

Burhanuddin Sunelwala
  • 5,318
  • 3
  • 25
  • 51
1

Have you tried the following?

returnSum = @(  roundf([returnSum floatValue] * 100) / 100 + roundf([payDoc.SOBTR floatValue] * 100) / 100  );

That will cause the float to only have two digits (approximately...) after the decimal point, not to just show two digits as the other comments and answers suggest.

Alternatively if you dont want to round the floats and just want to strip off the decimal digits you can write

returnSum = @(  (int)([returnSum floatValue] * 100) / 100.0 + (int)([payDoc.SOBTR floatValue] * 100) / 100.0  );
luk2302
  • 55,258
  • 23
  • 97
  • 137
0

Use [NSNumber numberWithInt:[returnSum floatValue]+[payDoc.SOBTR floatValue]];

Sanjay Mohnani
  • 5,947
  • 30
  • 46
-1

The best to do this is the following:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:[returnSum floatValue]+[payDoc.SOBTR floatValue]]];

NSLog(@"Result...%@",numberString);
fdlr
  • 101
  • 1
  • 11