[英]Set precision using decimalFormat error - Java
I am attempting to use the DecimalFormat java class for the first time, and I am running into a strange issue. 我试图第一次使用DecimalFormat java类,我遇到了一个奇怪的问题。 I would like 125.295 to round to 125.30. 我希望125.295回合到125.30。 I would think the format should automatically include the 0, but maybe I'm incorrect. 我认为格式应该自动包含0,但也许我不正确。
double num = 125.295;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_UP);
String str = df.format(num);
System.out.println(str); //this is yielding 125.3 instead of 125.30
Please help and thank you in advance! 请提前帮助并谢谢!
The DecimalFormat class treats '#' as "hide trailing zeroes" or '0' as "show the zeroes". DecimalFormat类将“#”视为“隐藏尾随零”或“0”视为“显示零”。 As per the API for DecimalFormat: 根据DecimalFormat的API:
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
So you should use DecimalFormat("#.00") instead of DecimalFormat("#.##") if you want it to show trailing zeroes. 因此,如果您希望它显示尾随零,则应使用DecimalFormat(“#。00”)而不是DecimalFormat(“#。##”)。
Try to use DecimalFormat
like this: 尝试像这样使用DecimalFormat
:
double num = 125.295;
DecimalFormat df = new DecimalFormat("###.00");
System.out.println("sum (DecimalFormat) : " + df.format(num));
Output: 输出:
125.30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.