Search code examples
javaandroiddecimalbigdecimalnumber-formatting

How to display 3 decimal points without round up?


I am making an app which need to display 3 decimal points i achieve this by NumberDecimal but the issue is if 4th digit is >5 then 3rd digit automatically increase. I want to show exact figure for ex :

Result           : 100.2356 
Output           : 100.236  // Applying NumberDecimal

Need this output : 100.235 // I need this output

This is my function :
public String setdecimal(float a) 
{
   NumberFormat formatter = new DecimalFormat("##.###");
   return formatter.format(a);

}

Solution

  • Use RoundingMode.FLOOR:

    NumberFormat formatter = new DecimalFormat("##.###");
    formatter.setRoundingMode(RoundingMode.FLOOR);
    

    Depending on how you want to handle negative numbers, you could also use RoundingMode.DOWN, which rounds towards zero.