Skip to content
Advertisement

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

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

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement