I'm doing
double x = distance/maxRange;
And want x to be equal to 1/3 for example when distance = 10 and maxRange = 30 instead of 0.
How do I got about having it properly formatted?
Thanks.
I'm doing
double x = distance/maxRange;
And want x to be equal to 1/3 for example when distance = 10 and maxRange = 30 instead of 0.
How do I got about having it properly formatted?
Thanks.
double x = (double) 1/3;
System.out.println(x); // result print 0.3333333333333333
You must convert your calculation to double, else you will get 0.
Assuming that distance
and maxRange
are ints, division will always result in 0
. What you have to do it turn one of them into a double
to force it to do floating-point division:
double x = ((double) distance) / maxRange;
double: The double data type is a double-precision 64-bit IEEE 754 floating point.
double z = (double) 1 / 3;
System.out.println("Result Using Double = " + z);
/*
Result Using Double = 0.3333333333333333
*/
double have 53-bit precision only see in https://en.wikipedia.org/wiki/Double-precision_floating-point_format.
So if you need more than 53-bit precision best option for it is used BigDecimal
For Example:
BigDecimal distance = new BigDecimal("1");
BigDecimal maxRange = new BigDecimal("3");
BigDecimal x = distance.divide(maxRange, /*precision-scale*/ 100, RoundingMode.HALF_UP);
System.out.println("Result Using BigDecimal=" + x);
/*
Result Using BigDecimal=0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
*/
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html