public static void main(String[] args) {
//第一種方法把String類型的小數保留後兩位
String a="1.9801";
//把Sting類型轉換爲double類型
double d=Double.parseDouble(a);
BigDecimal big=new BigDecimal(d);
big=big.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(big);
//第二種方法
DecimalFormat df=new DecimalFormat("0.00");
String dd=df.format(d);
System.out.println(dd);
}
Double乘以int會導致精度丟失,有很多位小數,解決方法如下:
String s = "0.18279442222";
Double d1 = Double.parseDouble(s);
/**
*Double乘以int則會導致小數位數很多,處理方法如下"%.2f"中.2是保留兩位小數,
*加%是變成百分數
*/
String d2 =String.format("%.2f",d1*100)+"%";
System.out.println(d2 );