如何根据输入长度更改DecimalFormat行为? [英] How can I change DecimalFormat behavior based on input length?

查看:250
本文介绍了如何根据输入长度更改DecimalFormat行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的 DecimalFormat 模式:

  //使用ThreadLocal确保线程安全。 
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 类指定此行为吗?

  • p>

    解决方案

      DecimalFormat(#,## 0.00#)


    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?

    解决方案

    DecimalFormat("#,##0.00#")
    

    这篇关于如何根据输入长度更改DecimalFormat行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆