How can I change DecimalFormat behavior based on input length?

喜欢而已 提交于 2019-12-04 20:31:42

问题


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?


回答1:


DecimalFormat("#,##0.00#")



回答2:


Have you tried to change the RoundingMode of your DecimalFormat instance?

Calling setRoundingMode(RoundingMode.FLOOR) should do the trick

See also setRoundingMode(java.math.RoundingMode)



来源:https://stackoverflow.com/questions/4429163/how-can-i-change-decimalformat-behavior-based-on-input-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!