Java – Android – 1 divided by 2 = 0

Android – 1 divided by 2 = 0… here is a solution to the problem.

Android – 1 divided by 2 = 0

I’ve been trying my new IOIO for android and need to find the frequency of the signal.
So I converted the signal to binary and then divided 1 by the time between 1. Although when I do this, I find that my output is 0. Then I decided to see what 1/2 gave me, and to my surprise it also gave 0!

Code:
Private float frequency = 1/2;

Could this be related to using Float.toString(frequency)?

Solution

This is an example of integer division. Try:

private float frequency = 1.0/2.0;

Java will execute 1/2, yielding 0.5. However, since Java treats this as an operation on integers (and 0.5 is not an integer), it truncates the decimal point and keeps only the integer part 0. By telling Java to use float (1.0 to 1), you tell it to keep the fractional part of the intermediate calculation.

Related Problems and Solutions