How can I truncate a double to only two decimal places in Java?

Johnny picture Johnny · Oct 13, 2011 · Viewed 302k times · Source

For example I have the variable 3.545555555, which I would want to truncate to just 3.54.

Answer

Bozho picture Bozho · Oct 13, 2011

If you want that for display purposes, use java.text.DecimalFormat:

 new DecimalFormat("#.##").format(dblVar);

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100;