Java Data Type How to - Format Floating Point Numbers and keep only three digits after decimal








Question

We would like to know how to format Floating Point Numbers and keep only three digits after decimal.

Answer

import java.text.DecimalFormat;
/*from   w  ww  . ja  va  2  s .c o  m*/
public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}

The code above generates the following result.