Java Display double in 2 decimal places
By:Roy.LiuLast updated:2019-08-17
In Java, there are few ways to display double in 2 decimal places.
Note
Read this RoundingMode
Read this RoundingMode
1. DecimalFormat
DecimalExample.java
package com.mkyong;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static DecimalFormat df2 = new DecimalFormat("#.##");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df2.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df2.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble : " + df2.format(input)); //3.14
df2.setRoundingMode(RoundingMode.UP);
System.out.println("double : " + df2.format(input)); //3.15
Output
double : 3.14159265359 double : 3.14 double : 3.14 double : 3.15
2. String.format
StringFormatExample.java
package com.mkyong;
public class StringFormatExample {
public static void main(String[] args) {
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.mkyong;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExample {
public static void main(String[] args) {
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
From:一号门
Previous:NameCheap domain name and Amazon EC2

COMMENTS