![](/img/trans.png)
[英]How can I specify the number of decimal places with NumberFormat in Java?
[英]How can I specify the number of decimal places of a BigDecimal to print?
我正在使用BigDecimal
,如下所示:
BigDecimal val = object.getValue();//it returns BigDecimal type value
val
包含12.2300。 我想在頁面上顯示12.23。 我怎樣才能做到這一點?
使用DecimalFormat
:
String formatted = new DecimalFormat("#.##").format(val);
您可以使用DecimalFormat或通過String操作對其進行操作
public static String format(BigDecimal big, int precision){
String bigS = big.toString();
int index = bigS.indexOf('.');
String add = bigS.substring(index, index + precision + 1);
String formatted = big.longValue() + "" + add;
return formatted;
}
public static void main(String[] args) {
BigDecimal big = new BigDecimal(2342342232.23232);
System.out.println(format(big, 2));
System.out.println(format(big, 3));
}
當然,DecimalFormat是聰明的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.