如何根据输入长度更改 DecimalFormat 行为?
我正在使用以下 DecimalFormat
模式:
// Use ThreadLocal to ensure thread safety.
private static final ThreadLocal <NumberFormat> numberFormat =
new ThreadLocal <NumberFormat>() {
@Override protected NumberFormat initialValue() {
return new DecimalFormat("#,##0.00");
}
};
这将执行以下转换:
1 -> 1.00
1.1 -> 1.10
1.12 -> 1.12
我现在有一个额外的要求。
1.123 -> 1.123
1.1234 -> 1.123
这意味着当
- 小数位数少于两位时,我将“填充”到小数点后两位。
- 恰好有两位或三位小数,我什么也不做。
- 小数点后三位以上,我会截断至小数点后三位。
我可以使用 DecimalFormat
类指定此行为吗?
I am using the following DecimalFormat
pattern:
// Use ThreadLocal to ensure thread safety.
private static final ThreadLocal <NumberFormat> numberFormat =
new ThreadLocal <NumberFormat>() {
@Override protected NumberFormat initialValue() {
return new DecimalFormat("#,##0.00");
}
};
This performs the following conversions:
1 -> 1.00
1.1 -> 1.10
1.12 -> 1.12
I now have an additional requirement.
1.123 -> 1.123
1.1234 -> 1.123
That means that when
- there are fewer than two decimal places, I will "pad" to two decimal places.
- there are exactly two or three decimal places, I will do nothing.
- there are more than three decimal places, I will truncate to three decimal places.
Can I specify this behavior with the DecimalFormat
class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过更改
DecimalFormat
实例的 RoundingMode ?调用 setRoundingMode(RoundingMode.FLOOR) 应该可以解决问题
另请参阅 setRoundingMode(java.math.RoundingMode)
Have you tried to change the RoundingMode of your
DecimalFormat
instance?Calling
setRoundingMode(RoundingMode.FLOOR)
should do the trickSee also setRoundingMode(java.math.RoundingMode)