-1

I am doing one program that calculates your BMI(body mass index),everything is working,but the result that appears,It's not right,because appears one number giant,like 24,99999 and I want that only appears something like 24,99.

My code is that :

  height = Double.parseDouble(txtHeight.getText());
                    weight =     Double.parseDouble(txtWeight.getText());           
                    bmi = height/weight;
                    bmi = weight/3.24;              


                    if(bmi < 17) {
                        lblBMI.setText("Your BMI is : " +bmi  + "," + " very underweight");
                    }

Example : If I put Height like 1,80 and Weight like 45 It will appears in the result as Your BMI is 13,88888888888888888.

PS : All the variables are Double.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Leandro Mont
  • 103
  • 2
  • 3
  • 11

1 Answers1

3

You can use the String.format() method like so:

double d = 7.9352;
String s = String.format("%.2f",d);

which will output 7.93 because the 2 in %.2f represents the number of digits that you want to include after the decimal point.

Alternatively if all you're doing is printing out the string you can use System.out.printf() like so:

System.out.printf("%.2f",d);
Spartak Singh
  • 268
  • 1
  • 8
  • 1
    While I'm not going to argue that this works (and works better then I expected it to), `NumberFormat` would allow you to format the value according to the current local which might be preferred. Still +1 ;) – MadProgrammer Sep 29 '15 at 03:48
  • Thanks man,It worked,I am very happy,thanks really. PS: And the code was very sample,nothing hard to understand. – Leandro Mont Sep 29 '15 at 03:57