/** * @author lautturi.com * Java example: Java DecimalFormat specify decimal places */ import java.text.DecimalFormat; import java.util.*; public class Lautturi { public static void main(String[] args) { float decimalNumber = 3.1415f; // DecimalFormat df = new DecimalFormat(); // df.setMaximumFractionDigits(2); // specify 2 decimal places // DecimalFormat df = new DecimalFormat("#.0"); // # - prints a digit if provided, nothing otherwise // . - indicates where to put the decimal seperator // 0 - prints a digit if provided, 0 otherwise // For Example: DecimalFormat df = new DecimalFormat("#.000"); // specify 3 decimal places System.out.println(df.format(decimalNumber)); } }
output:
3.141