This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 6 years ago.
Eg: I divide manually 8/3 = 2.666666.
When I divide in Java, I've got 8/3 = 2.0 instead.
How can I get the answer to display 2.667 or 2.67?
Thank you.
You are doing integer division hence result is integer
you need to do ((double)8)/3 to get desired result
Related
This question already has answers here:
Generate a random double in a range
(7 answers)
Using Math.round to round to one decimal place?
(9 answers)
Closed 4 years ago.
I am trying to round to the nearest decimal value, however, this line of code keeps returning a number between 0 and 1, I also want the output to be between 1 and 10. Where am I going wrong?
power[i] = rng.nextDouble();
Math.round(ThreadLocalRandom.nextDouble(1,10)*10)/10.0
You can use JDK's Math.round.
A detailed example can be found here.
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Retain precision with double in Java
(24 answers)
Closed 5 years ago.
Can anyone explain what's going on here? My calculator insists that the result of equitation is 13201.
double test = 132.01/0.01D;
System.out.println(test); <- 13200.999999999998
Probably, this is very simple question, but I really don't understand. Most of questions in SO on similar topic involves Integer and Double.
This question already has answers here:
Why does integer division code give the wrong answer? [duplicate]
(4 answers)
Closed 6 years ago.
I am doing simple calculation in java. Expected result is 51.3348 but what I am getting is 51.0, here is my calculation
float percent = (7819140000l-3805200000l)*100/7819140000l;
Is that problem with datatype? How can I resolve this to get value as 51.3348
Thanks in Advance
add an f to one of the values:
float percent = (7819140000l-3805200000l)*100f/7819140000l;
if yiu do not do it, Java will make a devision by long values
This question already has answers here:
Raising a number to a power in Java
(10 answers)
Closed 8 years ago.
I am trying to calculate the power as below but it is giving me 'bad operands type for binary operator '^'. I am guessing that it is a precedence issue but it still doesn't fix with inserting additional brackets
double pw = ((N - (df + 1))^2);
You should use java.lang.Math.pow(x,y)
Example: java.lang.Math.pow(2,3) returns 8
See this
http://www.tutorialspoint.com/java/lang/math_pow.htm
java.lang.Math.pow(double a, double b)
You can use static import for this.
This question already has answers here:
How can I handle precision error with float in Java?
(9 answers)
Closed 8 years ago.
some calculations with doubles return the wrong result.
E.g.
System.out.println(""+(0.05+0.01));
output
0.060000000000000005
What can I do to correct this error?
Doubles are not made for precise calculations (see Round to 2 decimal places) - for precise calculations, use BigDecimal instead.