![](/img/trans.png)
[英]ClassCastException when casting result of DecimalFormat.parse() when decimal is 0
[英]Is DecimalFormat not considering the decimal values when round it?
我正在嘗試格式化金額,但是十進制值未以正確的方式四舍五入。
public class Testing {
private java.text.DecimalFormat dispAmt;
public Testing() {
}
public static void main(String args[]){
Testing testing=new Testing();
testing.dispAmt = new java.text.DecimalFormat("##,##,##0.00");
// Line #8
System.out.println(testing.dispAmt.format(1974.545));
System.out.println(testing.dispAmt.format(1974.535));
}
}
OutPut:
=========
1,974.54
1,974.54
在上面的編中,第8行有什么問題。 為什么不將其舍入為“ 1,974.55”? 在哪里做錯! 請建議..
默認情況下, DecimalFormat
使用的舍入模式HALF_EVEN
其中
如果舍棄的分數左側的數字為奇數,則其行為與RoundingMode.HALF_UP相同。 行為與RoundingMode.HALF_DOWN相同。
在這種情況下, 1974.545
第二個最低有效位 4
是偶數,因此該值將四舍五入。 相反,值3
為奇數,因此在隨后的format
語句中四舍五入。
嘗試使用RoundingMode.HALF_UP
。
testing.dispAmt.setRoundingMode(RoundingMode.HALF_UP);
DecimalFormat#format不舍入! 它只是切斷默認情況下不顯示的值。
DecimalFormat使用半數舍入(請參閱ROUND_HALF_EVEN)進行格式化。
http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
您必須手動設置RoundingMode
dispAmt.setRoundingMode(RoundingMode.HALF_UP);
您需要通過使用setRoundingMode()方法對其進行設置來設置格式化程序的RoundingMode ,因為默認情況下,它不會舍入該值。
dispAmt.setRoundingMode(RoundingMode.CEILING); // Ex 1
dispAmt.setRoundingMode(RoundingMode.HALF_UP); // Ex 2 but I guess you need this in your case
有很多RoundingMode
可用。 請為此檢查文檔。
DecimalFormat是NumberFormat的一個具體子類,用於格式化十進制數字。 這並沒有舍入給定的數字。 信息這僅使用您提供的模式顯示數字。
DecimalFormat提供在RoundingMode中定義的舍入模式以進行格式化。 默認情況下,它使用RoundingMode.HALF_EVEN。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.