0

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.

Carson
  • 892
  • 4
  • 17
  • 31
  • 2
    You mean specifically `1/3` in console and not `0.33333...` – ΔȺȾΔ Sep 25 '15 at 02:22
  • 1
    Are `distance` and `maxRange` both `int`s (or `long`s)? – MadProgrammer Sep 25 '15 at 02:22
  • Either or would work 1/3 or 0.3333 I have to take that number and multiple it by something else to be returned. I'm using doubles. – Carson Sep 25 '15 at 02:25
  • Oh sorry right, I thought if I made x a double it would cast it for me and I didn't need distance and maxRange to be doubles. My bad, thank you! – Carson Sep 25 '15 at 02:27
  • 2
    possible duplicate of [Why the result of 1/3=0 in java?](http://stackoverflow.com/questions/4685450/why-the-result-of-1-3-0-in-java) – Dando18 Sep 25 '15 at 02:33
  • No way that 1/3 can be represented exactly in finite precision in decimal or binary. `0.333...` cannot be stored in any decimal type – phuclv Sep 25 '15 at 03:11

3 Answers3

2
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.

cw fei
  • 1,493
  • 1
  • 15
  • 32
1

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;
Will Richardson
  • 7,012
  • 6
  • 39
  • 50
0

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

Bhuwan Prasad Upadhyay
  • 2,399
  • 1
  • 24
  • 33
  • 1
    `double` doesn't have 64-bit precision, only 53 bits. And only `1.0/3` or `1/3.0` is needed, which is cleaner and shorter than casting – phuclv Sep 25 '15 at 03:12