1. 程式人生 > 實用技巧 >java 保留小數點後指定位數四種方法

java 保留小數點後指定位數四種方法


1
package com.itheima_01; 2 3 import java.math.BigDecimal; 4 import java.text.DecimalFormat; 5 import java.text.NumberFormat; 6 7 public class Demo03 { 8 public static void main(String[] args) { 9 /* 10 保留指定小數點後位數 11 */ 12 double a = 1.0123456789123456789; 13
//方法一:最簡單的方法,呼叫DecimalFormat類 14 //指定保留小數點後幾位 15 DecimalFormat df = new DecimalFormat(".0000000000"); 16 //轉換 17 String str = df.format(a); 18 //String轉double 19 double v = Double.parseDouble(str); 20 System.out.println(v); 21 22 //方法二:直接通過String類的format實現
24 String str2 = String.format("%.10f", a); 25 double v2 = Double.parseDouble(str2); 26 System.out.println(v2); 27 //方法三:通過BigDecimal實現 28 BigDecimal bd = new BigDecimal(a); 29 double v1 = bd.setScale(11, BigDecimal.ROUND_HALF_UP).doubleValue(); 30 System.out.println(v1);
31 32 //方法四:通過NumberFormat類實現 33 NumberFormat nf = NumberFormat.getNumberInstance(); 34 nf.setMaximumFractionDigits(12); 35 String s = nf.format(a); 36 double v3 = Double.parseDouble(s); 37 System.out.println(v3); 38 39 40 } 41 }