![](/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.