-1

I tried to make a small program that converts miles to kilometers back and forth, but whenever the number has 4 digits, the program instantly freezes

parts of code :

private double KmToMiles(double inputValue) {
    return(inputValue * 1.609344);  
    }
    private double MilesToKm(double inputValue) {
    return(inputValue * 0.621372);
    }

also

    double inputValue = Double.parseDouble(text.getText().toString());
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    text.setText(String.valueOf(nf.format(KmToMiles(inputValue))));


    text.setText(String.valueOf(nf.format(MilesToKm(inputValue))));
    jednotka.setText("kilometers");
    km.setChecked(false);

How do i make so the value returned has a small amount of decimals without retrieving error? If i swap double with integer and remove the number formatting, i get no error but the conversion is inaccurate with no decimals. Using doubles without NF i get too many decimals

Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
As Sfd
  • 3
  • 3
  • It works with number formatting... so what is the question? And have you looked into setting the maximum number of characters in your text box? http://stackoverflow.com/questions/3285412/limit-text-length-of-edittext-in-android – Display Name is missing Aug 13 '14 at 21:39
  • it did not work for me, but solution of person below did – As Sfd Aug 24 '14 at 15:34

1 Answers1

1

You can use the String.Format from the String class to specify the number of decimal places you want.

sample:

   String s = String.format("%.4f", KmToMiles(25)) //.4f means round it to 4 decimal places
   text.setText(s);

now that will result to 40.2336

If you want it to be 2 decimal places just change the modifier to %.2f

Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63