-1

I want to format a decimal number like this:

1234.5
   0.5

It mean the max number would be 9999.9 (4 characters before ".", 1 character after)

Jeeter
  • 4,960
  • 3
  • 41
  • 64
Hoa Nguyen
  • 170
  • 1
  • 7
  • 1
    There's the String.format method – Gilbert Le Blanc Jan 03 '13 at 16:32
  • possible duplicate of [How do I get whole and fractional parts from double in jsp/java?](http://stackoverflow.com/questions/343584/how-do-i-get-whole-and-fractional-parts-from-double-in-jsp-java) – jlordo Jan 03 '13 at 16:58

2 Answers2

4

Use DecimalFormat:

DecimalFormat df = new DecimalFormat("###0.0");
String str = df.format(yourDecimal);
CassOnMars
  • 6,077
  • 2
  • 31
  • 46
0

If you want to print your result, it may be simpler to use printf

for (double d : new double[]{1234.51111, 0.501})
    System.out.printf("%6.1f%n", d);

prints

1234.5
   0.5
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075