When I run,
public static void main(String[] args)
{
float num = 145/156;
System.out.println(num);
}
I get output 0.0, but expected output is 0.92948717. Any help is appreciated.
When I run,
public static void main(String[] args)
{
float num = 145/156;
System.out.println(num);
}
I get output 0.0, but expected output is 0.92948717. Any help is appreciated.
Division of an integer to an integer results an integer. So you are getting 0 because the data is getting truncated.
You need to type cast this to float
float num = (float)145/156;
145/156
is 0.something
, but because default numbers are coded as int
in Java, you'll loose what's after 0
because the result will be truncated.
You should cast one of the sides (The other will be implicitly cast).
use
public static void main(String[] args)
{
float num = (float)145/156;
System.out.println(num);
}
As, 145/156
is int/int
, so result is 0, type casted to float i.e 0.0
145 and 146 literals are integer and / is integer division.
try to use just 145f (the f denote float) to force the decimal division.
You just need to cast
at least one of the operands to a float
float num = (float) 145 / 156;
or
float num = 145 / (float) 156;
145
and 156
are both of type int
, thus the result is 'interpreted' as an integer (everything behind the dot is truncated, so 0.92948717 will become 0), and saved into a variable of type float
, which is presented as 0.0
.
Cast at least one of both numbers to a float in order to signal the machine to handle the result as a float.
float num = (float) 145 / 156;
Alternatively, you can suffix the number with an f
to signal the machine to 'interpret' the number as a float:
float num = 145f / 156;
here what you are doing is like,
int a = 145;
int b = 156;
float num = a/b;
that's why you get point zero at the end. So to get the expected output you must first cast it as follows
float num = (float) a/b;
The numbers you have used are integers. Integer division in Java results in an integer. Apart from casting the first number to float to force a conversion and proper floating-point operation, like this:
float num = (float)145/156;
you can also write the expression like this:
float num = 145f/156;
This way, by adding f
at the end, the number 145f
is interpreted as float.
145 and 156 are both ints, make sure at least one has decimals. Example:
float num = (145.0 / 156);