Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDecimalNumber subtraction

I need to subtract 0.5 from number a and set the answer to number b. My code looks like it would work but I'm not sure what I'm doing wrong. The error I get Is on the subtraction line, the error says incompatible type for argument 1 of 'decimalNumberBySubtracting:'.

Heres my header: (Note: I only showed the numbers because the header is large)

    NSDecimalNumber *a;
    NSDecimalNumber *b;

Heres the rest: (Assume this is in an IBAction)

    b = [a decimalNumberBySubtracting:0.5];

If anyone knows how to properly subtract any help would be appreciated.

like image 580
nosedive25 Avatar asked Apr 17 '10 12:04

nosedive25


People also ask

What is NSDecimalNumber?

The NSDecimalNumber Class is a subclass of the NSNumber class and has methods for performing arithmetic operations without loss of precision and with predictable rounding behavior. This makes it a better choice for representing currency than C's floating-point data type like double.


1 Answers

The parameter must be an NSDecimalNumber too.

NSDecimalNumber *half = [NSDecimalNumber decimalNumberWithString:@"0.5"];
b = [a decimalNumberBySubtracting:half];

In your example you're using a float. There are two reason that cannot work:

  • Objective-C cannot distinguis a float and an object at runtime, meaning you cannot supply a float instead of an object.
  • Most decimal numbers cannot be described exactly in a binary system, therefore you have to work exclusively with decimal or binary numbers, but not both.
like image 80
Georg Schölly Avatar answered Sep 29 '22 10:09

Georg Schölly