user2264210
user2264210

Reputation: 1

NSDecimalNumber addition losing decimal places

I am trying to make a calculator iphone app and my teacher said we had to use NSDecimalNumber. I am having a lot of trouble with it. I am trying to get the addition part of it right, but I am having trouble when adding a number like 1.24 to a whole number like 33. The result comes out to be 34 when I want it to be 34.24. Does anyone know how to make it so it comes out this way? Here is the relevant parts of the code

    -(void)outputNumber: (NSDecimalNumber*) number
{
    //used to format number of decimal places
    NSNumberFormatter* formatter = [[[NSNumberFormatter alloc] init] autorelease];
    [formatter setMaximumFractionDigits:self.afterDecimal];

    //output the number to calculator
    NSString* formatNumber = [formatter stringFromNumber:[NSNumber numberWithDouble:[number doubleValue]]];
    self.inputLabel.text = [NSString stringWithFormat: @"%@", formatNumber];

    if (self.isWaiting == TRUE) {
        self.numberB = number;
        //change button title default color
        [self.myButton setTitleColor:[UIColor colorWithRed:.196 green: .3098 blue: .52 alpha: 1] forState: 0];
    }
    else {
        self.numberA = number;
    }
}
if (self.binaryTag == 6) {
        self.numberC = [self.numberB decimalNumberByAdding: self.numberA]; 
    }

Upvotes: 0

Views: 215

Answers (1)

Sulthan
Sulthan

Reputation: 130102

Actually NSNumberFormatter doesn't work correctly with NSDecimalNumber. It converts everything to a double first.

When using NSDecimalNumber, try to use its own methods to round it and then convert it into NSString. With a NSNumberFormatter you will just lose the precision.

Upvotes: 0

Related Questions