Houranis
Houranis

Reputation: 361

I cannot get decimal after doing a simple division math

Look at my simple math script

double s = 3/2;
NSLog (@"%.2f",s);

I get 1, it should be 1.50

How can I fix it?

Upvotes: 0

Views: 69

Answers (3)

rakeshNS
rakeshNS

Reputation: 4257

3 and 2 are integers. So 3/2 is 1. You should try instead

double s = 3.0/2.0;
NSLog (@"%1.2f",s);

It will give you the right answer.

Upvotes: 0

poncha
poncha

Reputation: 7866

try double s = 3/2.0 both 3 and 2 are integers, so despite receiver being double, you still get an int result and it is then converted to double

Upvotes: 0

yuji
yuji

Reputation: 16725

double s = 3/2 means divide the int 3 by the int 2, and then cast the result (which is the int 1) to a double (giving you 1.0).

You want this:

double s = 3.0/2.0;

Upvotes: 4

Related Questions