1

I am facing an issue in decimal point I want to get only two decimal points only so I used this below code

 public class TestDateExample1 {
  public static void main(String[] argv){
      double d = 2.34568;
         DecimalFormat f = new DecimalFormat("##.00");
         System.out.println(f.format(d));
    }
  }

when I run this code the output is 2.35 but I dont need any increment when the decimal point is higher than "5" I need exact decimal point like 2.34.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sairam Sattar
  • 35
  • 1
  • 3

2 Answers2

3

You could use DecimalFormat#setRoundingMode to control how the rounding is done, and specify you always want to round down (truncate):

DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.DOWN);
System.out.println(f.format(d));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

DecimalFormat.setRoundingMode() needs to be set to RoundingMode.FLOOR

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
user2862544
  • 415
  • 3
  • 13
  • 1
    As @Mureinik mentioned, it's better to use `RoundingMode.DOWN` in order to support the case where the double is negative. That is, unless the OP intends to round in the opposite direction if the number is negative ;) – Nir Alfasi Aug 13 '17 at 17:59