1

I want to round of my double to 3 decimal places in java.

I don't want to trim off the zero. So if my double is 2.34, I still want it as 2.340.

Prashant
  • 11
  • 1
  • 2
  • 1
    possible duplicate of [Round a double to 2 significant figures after decimal point](http://stackoverflow.com/questions/2808535/round-a-double-to-2-significant-figures-after-decimal-point) – tchrist Sep 05 '12 at 23:23

5 Answers5

8
DecimalFormat myFormatter = new DecimalFormat("0.000");
String output = myFormatter.format(2.34d);
dhblah
  • 9,751
  • 12
  • 56
  • 92
4
String res = String.format("%.3f", 2.34);

or if you want to print

System.out.printf( "%.3f",2.34);
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
keshav84
  • 2,291
  • 5
  • 25
  • 34
1

use setMinimumFractionDigits and setRoundingMode

    final DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(3);
    df.setRoundingMode(RoundingMode.HALF_UP);
    df.format(2.34);
Lealem Admassu
  • 458
  • 4
  • 10
1

Use the following decimal format: 0.000

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • @prashant be aware that there's a difference in how a number is stored in the computer, and how it is displayed. This answer, and keshu's, show how to display the number with the trailing 0. It isn't actually being stored that way but that's unimportant. – Tony Ennis Sep 24 '10 at 13:57
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483