Search code examples
androidmathreturnreturn-valuemilliseconds

Simple math always returning 0


In my app I have a time in milliseconds (between 0 and 60000) divided by a certain value (In the current example it's 60000) Then, I times that by 100.

However, when printing the answer into the log, it always returns 0.

This is my code:

countDownTimer = new CountDownTimer(activityDuration, 1000) {
        @Override
        public void onTick(long timeLeftInMillis) {
            int minutes = (int) (timeLeftInMillis / 1000) / 60;
            int seconds = (int) (timeLeftInMillis / 1000) % 60;

            String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
            countDownTimerTextView.setText(timeLeftFormatted);

            System.out.println("L: " + timeLeftInMillis); // Returns correctly. Values between 0 and 60000
            System.out.println("Activity Duration: " + activityDuration); // Returns correctly. 60000
            System.out.println("Progress: " + (timeLeftInMillis / activityDuration) * 100); // Returns 0
        }

        @Override
        public void onFinish() {

        }
    }.start();

Solution

  • timeLeftInMillis / activityDuration is integer division and is always truncated to the nearest integer.

    You need to cast to a float or double before doing the divsion i.e. ((double)timeLeftInMillis / activityDuration) * 100)