javadoubletruncatedecimalformat

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.


Solution

  • 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;