0

I have a double value which could be either 9.2 or 13.45 or 198.789 or 110.8. How do I format this to 9.2000 or 13.4500 198.7890 or 110.8000

Jason
  • 12,229
  • 20
  • 51
  • 66

6 Answers6

4

This SO post can be of help.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
2

Look into the Decimal Format class.

Jim
  • 22,354
  • 6
  • 52
  • 80
2

new DecimalFormat("#0.0000").format(9.2); //"9.2000"

pinichi
  • 2,199
  • 15
  • 17
1

See: The DecimalFormat Class under

http://download.oracle.com/javase/tutorial/java/data/numberformat.html

trickwallett
  • 2,418
  • 16
  • 15
1

Have a look at DecimalFormat

0

You can use String.format() to some extent. For example:

String.format("%07.3f", 1.23d); //prints 001.230

The format is %0<width>.<precision>f where, <width> is the minimum number of character (including the dot) that should be printed padded with 0's (in my example there are 7 characters); <precision> is the number of digits after the decimal point.

This method will work for simple formatting, and you cannot control the rounding (rounding is is half-up by default).

rodion
  • 14,729
  • 3
  • 53
  • 55