-2

I was working on an Android application that scales user input so I can use a dial to visually represent where the input is from a certain scale.

I've encountered something interesting. What I was doing was I multiplied the user input by 6/5 to come up with the angle that the dial needs to be in to correspond to the user input. However, it seemed like there was something wrong with the angle I was getting so I decided to log these statements:

Log.e("", "current speed = " + currentSpeed);
Log.e("", "raw results = " + ((6/5)*(currentSpeed)));

And what was happening was that the currentSpeed seemed to be getting multiplied by 1. I then tried to use the decimal form of 6/5 which was 1.2, and then I got my desired results.

At first, I thought that Android rounded my factor of 6/5 to 1 because I didn't declare it as a double, so what I tried next is:

double factor = 6/5;

And then I used that in my equation. However, it seemed that I still was getting 1 and not 1.2 as my factor.

My question is this: Why does it seem that Android does not handle fraction operations well? Usually I wouldn't have a problem since 6/5 conveniently converted to 1.2. However, in situations wherein the fraction does not convert nicely to a decimal, then we'd have problems with accuracy. Are there ways to use fractions reliably when doing math operations in Android?

halfer
  • 19,824
  • 17
  • 99
  • 186
Razgriz
  • 7,179
  • 17
  • 78
  • 150

1 Answers1

1

How java manages division (pseudocode):

if ( is_int( numerator ) && is_int( denominator ) ) :
    d = int( numerator / denominator )
else :
    d = float( numerator / denominator )

Hence 6/5 == 1 in java.

So cast your denominator to a float or double, then divide.

Also, remember to check that denominator is not 0 (just in case).

rask004
  • 552
  • 5
  • 15