-1

What is the best way to convert a double xx.xx to the following strings in Java?

  • 22.0 to 22
  • 22.1 to 22.1
  • 22.22 to 22.22
  • 22.00 to 22

If the decimal part is 0, just need the whole number.

spongebob
  • 8,370
  • 15
  • 50
  • 83
MukeshKoshyM
  • 514
  • 1
  • 8
  • 16

2 Answers2

2

Use the class DecimalFormat

double d = 2.0;
DecimalFormat formatter = new DecimalFormat("0.##");
String formated = formatter.format(d).toString();
Gabriel Espinel
  • 358
  • 2
  • 9
0

The code finally decided is as below.

If you use DecimalFormat and specify # in the pattern it only displays the value if it is not zero.

    Double d=22.00 
    DecimalFormat format = new DecimalFormat("###.##");
    format.format(d);
MukeshKoshyM
  • 514
  • 1
  • 8
  • 16