This question already has answers here:
Unexpected result in long/int division
(7 answers)
Closed 8 years ago.
I am trying to learn interesting behaviour of java. Please explain
double z = 1/3;
System.out.println(z);
This program return 0.0 where as
double z = 1/3d;
System.out.println(z);
This program prints 0.333333. What is the difference.
The first one is an integer division really. It divides an integer by another integer (the result of which is again an integer) and assigns the result to a double variable.
Only the second one yields a double as result.
integer / integer => result is integer, even though assigned to a double variable
integer or double / double => result is double
first example will divide integers and assign them to your double "z", second divides doubles in the first place
Integer/Integer is an Integer even if you assign it to a holder variable of type double.To get a double precision value,you need to do your arithmetic operations using double variables
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14
This question already has answers here:
How to multiply a BigDecimal by an integer in Java
(3 answers)
Closed 8 years ago.
I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below
Bigdecimal x=BigDecimal.valueOf(0.0004)
Now I am trying to multiply as x*100 but I am getting below error.
Error: The operator * is undefined for the argument type(s) BigDecimal, int
Because of this error if I use this without bigdecimal again it is converting to EXponential.
Can any one please suggest me the way to multiply Bigdecimal and int.
googled a lot but couldn't find the correct solution.
Thanks for your time
You can use BigDecimal.multiply to multiply your BigDecimal.
However, the int value of 0.0004 * 100 will be 0, which is probably not what you want.
Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your Number.
Here's an example:
BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));
Output
y is 0.04000 z is 0
y (2 fraction digits) is 0.04
BigDecimal's are objects. They don't have normal operators.
Instead of a normal multiplication operator like x*10, you need to call the method multiply in BigDecimal:
x = x.multiply(new BigDecimal(10));
If you want to store it in a new value:
BigDecimal n = x.multiply(new BigDecimal(10));
And to convert that to a primative:
double d = n.doubleValue();
int i = n.intValue();
However, if you're trying to use decimals, why not just use a double:
double x = 0.0004;
double n = x*100;
Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365; is telling me that answer is 0. Or any other combination of double for that matter, its just truncating the decimal and I just don't know why.
364/365 performs integer division (truncates the decimal).
Try double answer = 364.0/365; to force it to perform floating point division.
Something like:
double days_in_year = 365;
double answer = 364/days_in_year;
would work as well, since one of the operands isn't an integer.
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
double answer = 364d / 365d;
More info here:
http://mindprod.com/jgloss/division.html
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated int.
What you need is:
double answer = 364 / 365.0;
or
double answer = 364 / (double) 365;
The reason is that the default type of integer literals in java is int and all the result of all int based arithemetic is type casted back to int. Hence though your answer is 0.997, when it is typecasted back it becomes 0:
(int)0.997 = 0
So you can do like this:
364.0/365.0
or
((float)364)/365
All the above answers are right, would just like to add that it is all about GIGO.
double answer = 364/365;
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
double ans = 4.0/0;
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
double ans = 4/0;
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.