Get warning when convert double to NSDecimalNumber

360 views Asked by At

I'm trying to convert a double to an NSDeciamlNumber. Here is my code:

- (NSDecimalNumber *)myMethod {
    double amount = 42;
    ...

    return [NSDecimalNumber numberWithDouble:amount]; // Get warning here
}

But I get the following warning:

Incompatible pointer types returning 'NSNumber *' from a function with result type 'NSDecimalNumber *'

What am I doing wrong, and how can I fix it?

5

There are 5 answers

0
shiva tripathi On BEST ANSWER

numberWithDouble: method of NSDecimalNumber returns NSNumber. In your method you want to return decimal so its OK if you allocate a new NSDecimalNumber with the decimal value (amount in your example).

May use the following way to get rid of the error:

-(NSDecimalNumber *)myMethod 
{ double amount = 42; ...
    return [[NSDecimalNumber alloc] initWithDouble: amount];
}
0
agy On

According to documentation [NSDecimalNumber numberWithDouble:_] returns a NSNumber so you should change the method declaration

- (NSNumber *)myMethod {
    double amount = 42;
    ...

    return [NSDecimalNumber numberWithDouble:amount]; // Get warning here
}
0
iAnurag On

Try this. It may work out

- (NSNumber *)myMethod {
   double amount = 42;
   [NSNumber numberWithDouble:amount]
  return [NSDecimalNumber numberWithDouble:amount]; 
}
0
Clement Prem On

numberWithDouble: method returns an NSNumber object but you suppose to return NSDecimalNumber.

Change it to

- (NSDecimalNumber *)myMethod {
    double amount = 42;

    return [[NSDecimalNumber alloc]initWithDouble:amount];
}
0
Santu C On

Try below code-

- (NSDecimalNumber *)myMethod {
    double amount = 42;
    ...

    return [[NSDecimalNumber alloc] initWithDouble: amount]; 
}