如何根据输入长度更改 DecimalFormat 行为?

发布于 2024-10-07 05:26:32 字数 682 浏览 0 评论 0原文

我正在使用以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

简单气质女生网名 2024-10-14 05:26:32
DecimalFormat("#,##0.00#")
DecimalFormat("#,##0.00#")
天暗了我发光 2024-10-14 05:26:32

您是否尝试过更改 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 trick

See also setRoundingMode(java.math.RoundingMode)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文