Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit decimal places using printf in Java?

Tags:

java

format

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);
like image 259
Champigne Avatar asked Sep 17 '26 19:09

Champigne


2 Answers

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
like image 187
Marc B Avatar answered Sep 19 '26 08:09

Marc B


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.

like image 28
Óscar López Avatar answered Sep 19 '26 09:09

Óscar López