/** * java 如何保留指定位數的小數 * @author Administrator * */ public class Test04 { public static void main(String[] args) { //保留小數點位數 double pi = 3.1415; //四舍五入函數 System.out.println(Math.round(3.5)); //取值范圍小的,和取值范圍大的做運算,整個表達式會被提升成大的數據類型 //掌握這種方法 System.out.println(pi*1000); System.out.println(Math.round(pi*1000)/1000.0);//結果為3.142
//Math.round(a)為四舍五入方法
DecimalFormat df = new DecimalFormat(".000"); String str = df.format(pi); //String 轉化為doouble double result2 = Double.parseDouble(str); System.out.println(result2); //String str轉換為double String str2 = String.format("%.3f", pi); double results = Double.parseDouble(str2); System.out.println(results); BigDecimal bd = new BigDecimal(pi); double result4 = bd.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(result4); } }