In Java, there are few ways to display double
in 2 decimal places.
Possible Duplicate
How to round double / float value to 2 decimal places
1. DecimalFormat(“0.00”)
We can use DecimalFormat("0.00")
to ensure the number is round to 2 decimal places.
DecimalExample.java
package com.favtuts.classic; import java.math.RoundingMode; import java.text.DecimalFormat; public class DecimalExample { private static final DecimalFormat df = new DecimalFormat("0.00"); public static void main(String[] args) { roundDecimalWithDecimalFormat(); } static void roundDecimalWithDecimalFormat() { double input = 3.14159265359; System.out.println("double : " + input); System.out.println("double : " + df.format(input)); //3.14 // DecimalFormat, default is RoundingMode.HALF_EVEN df.setRoundingMode(RoundingMode.DOWN); System.out.println("\ndouble (RoundingMode.DOWN) : " + df.format(input)); //3.14 df.setRoundingMode(RoundingMode.UP); System.out.println("double (RoundingMode.UP) : " + df.format(input)); //3.15 } }
Output
double : 3.14159265359
double : 3.14
double (RoundingMode.DOWN) : 3.14
double (RoundingMode.UP) : 3.15
Note
You may interest at this article – DecimalFormat(“#.##”) or DecimalFormat(“0.00”)
2. String.format(“%.2f”)
We also can use String formater %2f to round the double to 2 decimal places. However, we can’t configure the rounding mode in String.format
, always rounding half-up.
StringFormatExample.java
package com.favtuts.classic; import java.math.RoundingMode; import java.text.DecimalFormat; public class DecimalExample { private static final DecimalFormat df = new DecimalFormat("0.00"); public static void main(String[] args) { roundDecimalWithStringFormat(); } static void roundDecimalWithStringFormat() { double input = 3.14159265359; System.out.println("double : " + input); System.out.println("double : " + String.format("%.2f", input)); System.out.format("double : %.2f", input); } }
Output
double : 3.14159265359
double : 3.14
double : 3.14
3. BigDecimal
BigDecimalExample.java
package com.favtuts.classic; import java.math.BigDecimal; import java.math.RoundingMode; public class DecimalExample { public static void main(String[] args) { roundDecimalWithBigDecimal(); } static void roundDecimalWithBigDecimal() { double input = 3.14159265359; System.out.println("double : " + input); BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP); double newInput = bd.doubleValue(); System.out.println("double : " + newInput); } }
Output
double : 3.14159265359
double : 3.14
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/classic