Why does Java
return a 0
when I divide 10/60
?
the code I tried is
double pay_per_minute = (10/60);
10 being the pay rate per hour and 60 being the minutes.
Why does Java
return a 0
when I divide 10/60
?
the code I tried is
double pay_per_minute = (10/60);
10 being the pay rate per hour and 60 being the minutes.
Because you're building an integer. When you store it in a double
variable, it's already too late : it's 0
.
Do
double pay_per_minute = (10.0/60);
If you have variables, cast them :
double pay_per_minute = ((double)pay_per_hour) / 60;
any primitive digit in java is treated as an integer, so when you do 10/60, it is integer division and due to precision loss it is giving 0
Here 10
and 60
takes as int values and then you get int
dividing result it is 0
then you get answer as 0
. use following way.
double a=10;
double b=60;
double div=a/b;
you need to type cast it first because by default numericals are considered as integers
double pay_per_minute = ((double)10/60);
System.out.println(pay_per_minute);
output 0.16666666666666666
double pay_per_minute = (10/60);
Here, you are dividing integer 10 by integer 60. So, this is like doing
int temp = 10/60;
double pay_per_minute = double(temp)
your temp will be 0 (since 10/60 is 0 when considered as integer division)
You need to do, double pay_per_minute = (10.0/60);