Jacob Clark
Jacob Clark

Reputation: 3447

Objective-C Double, Long Calculation

I am trying to calculate a long value divided by an integer to give me what I would expect to be a double, although the result I am getting is 0. The code I am using...

double daysByYear = daysSinceBirthdayToService/365;
NSLog(@"%d", daysByYear);

In this code, daysSinceBirthdayToService variable is a Long Double which can be NSLogged using the following code (long)daysSinceBirthdayToService

It is declaired in the header file as a property of

@property (nonatomic) NSInteger daysSinceBirthdayToService;

Can anybody help me out with this, thanks!

Upvotes: 2

Views: 8604

Answers (3)

insanebits
insanebits

Reputation: 838

Can it be that %d outputs decimal number not a double?

Upvotes: -1

mmmmmm
mmmmmm

Reputation: 32661

The issue is that / between two longs will do an integral division.

To force a floating point division at least one of the operands needs to be cast to double.

e.g.

double daysByYear = daysSinceBirthdayToService/(double)365;

or if you have a literal make that a double by adding a decimal point

double daysByYear = daysSinceBirthdayToService/365.0;

Upvotes: 6

Ben Lu
Ben Lu

Reputation: 3042

double daysByYear = daysSinceBirthdayToService/365.0;

Upvotes: -1

Related Questions