There are multiple approaches to display double or float data with 2 decimal places in Java. The post presents a way using DecimalFormat.
1 2 3 4 5 |
double d = 31.236567; DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(d)); |
output:
31.24
If you want to format any double number to currency supported format with 2 decimal places, (for example, change 4 to 4.00, 45.5 to 45.50), we can implement it as
1 2 3 4 5 6 7 8 9 10 |
public static String format(double amount) { DecimalFormat df = new DecimalFormat("#.##"); String str = df.format(amount); int index = str.indexOf("."); if(index == -1) { return str +".00"; } else if((str.length() - 1 - index) == 1) { return str + "0"; } else { return str; } } |