"(int) Math.ceil (double)" always returns 1, even if the value is greater than 1

I am creating an Android application and I need to calculate the speed of the device. I do this by taking the average of the speeds of the earlier locations. However, I need the speed to be km/h

like int

, so I use

(int)Math.ceil(speedAsDouble)

      

However, it is always equal 1

, even if speedAsDouble

equal 7.8825246

or 0.58178

.
This is the important part of the code:

// Create a variable for the speed
double speedAsDouble = 0d;

// Loop through the last points
for(int i = 0; i < lastPoints.size() - 1; i++)
{
    // Add the speed for the current point to the total speed
    speedAsDouble += (double)(lastPoints.get(i).distanceTo(lastPoints.get(i + 1)) / (lastPoints.get(i + 1).getTime() - lastPoints.get(i).getTime()));
}

// Divide the speed by the number of points
speedAsDouble /= (double)lastPoints.size();
// Convert the speed to km/h
speedAsDouble *= 3.6d;

// Log the speed
System.out.println("Speed: " + speedAsDouble);

      

Then I round the number and pass it to int as described above using

int speedAsInt = (int)Math.ceil(speedAsDouble)

      

and write down the number again with

System.out.println("Rounded speed: " + speedAsInt)

      

Here is part of the log:

05-17 12:00:42.605  24610-24610/package I/System.out﹕ Speed: 0.0
05-17 12:00:42.635  24610-24610/package I/System.out﹕ Rounded speed: 0
05-17 12:00:43.625  24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4
05-17 12:00:43.645  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:44.595  24610-24610/package I/System.out﹕ Speed: 5.27003884781152E-4
05-17 12:00:44.615  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:45.595  24610-24610/package I/System.out﹕ Speed: 4.216031078249216E-4
05-17 12:00:45.635  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:46.595  24610-24610/package I/System.out﹕ Speed: 0.002668234216980636
05-17 12:00:46.605  24610-24610/package I/System.out﹕ Rounded speed: 1

      

I spent a lot of time on this trying to use different types of variables and variables, but with no success.

+3


source to share


2 answers


All of the outputs you output (except the first, which is 0) are Speed

less than 1 ( 7.026718463748694E-4

, 5.27003884781152E-4

etc.). Pay attention to the negative indicator.



So it's no surprise that it ceil

returns 1.

+4


source


Please take a closer look at your output, for example:

05-17 12:00:43.625 24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4



doesn't mean you have 7.02, but 0.000702. At the end there is E-4

. When you use ceil, it will always return 1.

+1


source







All Articles