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.
Related
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:
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
This question already has answers here:
How many significant digits do floats and doubles have in java?
(6 answers)
Closed 7 years ago.
I have a problem when it comes to calculating pi with more than 15 decimal places(i used double).
My result looks quite good except my variable is limited to 15 decimal places:
3.140592653839794
Anybody could tell me what i have to do if i want more decimal places?
Thanks and Greeting!
Use java.math.BigDecimal instead of double for arbitrary (finite) precision.
This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Closed 7 years ago.
The title says it all. Right now if I input a number like 100.50, in my program it prints as 100.5. Is there an easy way to make the program recognize the zero?
You can do this trick.
String s = String.format("%.2f", 100.50);
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.