2

I'm trying to truncate to the third decimal point using printf in Java, but I keep getting to only the second decimal point. Here's the line of code where I was attempting this:

System.out.printf("The speed in ft/sec is %6.2f\n", time);
Uyric
  • 646
  • 7
  • 17
Champigne
  • 25
  • 2
  • 8

2 Answers2

7

Try %6.3f instead. the format is

%(before).(after)(type)
    6         3    f

    6 -> 6 digits before the decimal
    3 -> 3 digits AFTER the decimal
Marc B
  • 356,200
  • 43
  • 426
  • 500
5

Try this:

System.out.printf("The speed in ft/sec is %6.3f\n", time);

The above will round to three decimal places (not "truncate" them). The only difference is in the value after the dot.

Óscar López
  • 232,561
  • 37
  • 312
  • 386