MichalCh
MichalCh

Reputation: 241

How to format numbers on Android

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

Upvotes: 1

Views: 8373

Answers (3)

kayton
kayton

Reputation: 3759

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

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

Then call:

df.format(someDoubleValue);

Upvotes: 1

badjr
badjr

Reputation: 2296

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:

Upvotes: 2

Chris
Chris

Reputation: 4231

Use String.format:

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

Upvotes: 4

Related Questions