java round double to 2 decimals place

java round double to 2 decimals place

how to round double to 2 decimal places in java

/**
 * @author lautturi.com 
 * Java example: java round up double to 2 decimal places
 */

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class Lautturi {
	
	public static void main(String[] args) {
		double pi = 3.14159;
		double roundOff = Math.round(pi * 100.0) / 100.0;
		// Or
		// double roundOff = (double) Math.round(pi * 100) / 100;
		// Or
		String roundStr = String.format("%.2f", pi);
		
		// Or
		BigDecimal bd = BigDecimal.valueOf(pi);
	    bd = bd.setScale(2, RoundingMode.HALF_UP);
	    double roundPi = bd.doubleValue();
	    
		System.out.println(roundOff);
		System.out.println(roundStr);
		System.out.println(roundPi);
	}
}
S‮cruo‬e:www.lautturi.com

output:

3.14
3.14
3.14
Created Time:2017-09-29 13:39:56  Author:lautturi