I want to round of my double to 3 decimal places in java.
I don't want to trim off t开发者_C百科he zero. So if my double is 2.34, I still want it as 2.340.
DecimalFormat myFormatter = new DecimalFormat("0.000");
String output = myFormatter.format(2.34d);
String res = String.format("%.3f", 2.34);
or if you want to print
System.out.printf( "%.3f",2.34);
Use the following decimal format: 0.000
use setMinimumFractionDigits and setRoundingMode
final DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(3);
df.setRoundingMode(RoundingMode.HALF_UP);
df.format(2.34);
Following on from Tony Ennis's comment, you can't round a floating-point variable to a specific number of decimal places, or digits, without converting it into base-10. That's what the answers above are doing, and they are also converting it into displayable text.
精彩评论