1

i am learning to program mobile aplications on Android. My first app is a unit converter. Everithing is working for now, but i have a question about formating numbers. I hava this code to get text from buttons and to convert the appropriet output:

if (bPrevodZ.getText() == "milimeter"){
    if (bPrevodDo.getText()=="kilometer"){
        String PomocnaPremenna = jednotkaZ.getText().toString();
        double cisloNaPrevod = Double.parseDouble(PomocnaPremenna);
        cisloNaPrevod = cisloNaPrevod*0.0000001;
        vysledok.setText(Double.toString(cisloNaPrevod));
    }

The final result is "cisloNaPrevod", but i have problems to show a good format of that number. For example: 12345 mm = 0,0012345 km this is good right ? :)

but if i convert: 563287 mm = 0.05632869999999995 this is bad :) i need it to show 0.0563287

Thx for any help

MichalCh
  • 201
  • 3
  • 15
  • **Never** compare strings with `==`, use `.equals();`. Why? Read [this question](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo Jan 06 '13 at 21:29

3 Answers3

4

Use String.format:

String.format("%.6f", cisloNaPrevod);
Chris
  • 4,133
  • 30
  • 38
2

If you want your number to always have 6 significant figures, use

vysledok.setText(String.format("%.6g", cisloNaPrevod));

giving the result 0.0563287.

If you want to round to 6 numbers after the decimal place, use

vysledok.setText(String.format("%.6f", cisloNaPrevod));

giving the result 0.056329.

Here's some good resources that cover number formatting:

badjr
  • 2,166
  • 3
  • 20
  • 31
1

If it's something you're going to do often, perhaps you should use DecimalFormat.

DecimalFormat df = new DecimalFormat("#.#######"); 

Then call:

df.format(someDoubleValue);
snotyak
  • 3,709
  • 6
  • 35
  • 52