Search code examples
javaandroiddecimallong-integercountdown

Easy way to show Decimal of Long via CountDownTimer - Android


I have working code but it seems a bit strange that I have to gimmick my way around showing a decimal place on CountDownTimer but I haven't found anything that does it easier (obviously).

Here is the working Code I currently have:

    final String tempTitle = TextView.getText().toString();

    new CountDownTimer(10000, 100) {

                 public void onTick(long millisUntilFinished) {
                     String timeDown = String.valueOf(millisUntilFinished / 100);
                     String secTime="0";
                     String sec10th="0";
                     if (Long.valueOf(millisUntilFinished) < 1000) {
                     secTime ="0";
                     sec10th = timeDown.substring(0,1);
                     }else{
                     secTime=timeDown.substring(0,1);
                     sec10th = timeDown.substring(1,2);
                     }

                     TextView.setText("Start in: " + secTime + "." + sec10th);
                 }

                 public void onFinish() {
                     TextView.setText(tempTitle);
                 }
              }.start(); 


    }

Solution

  • divide by 100.0 so you dont do integer division.

    Edit per your comment: you could do

    DecimalFormat df=new DecimalFormat("#.##"); //import java.text.DecimalFormat;
    String timeDown=df.format(millisUntilFinished/100.0);
    

    or #.### etc depending on how many decimals you want...