Java货币编号格式 [英] Java Currency Number format

查看:167
本文介绍了Java货币编号格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将小数格式化如下:

Is there a way to format a decimal as following:

100   -> "100"  
100.1 -> "100.10"

如果是圆数,则省略小数部分。否则用两位小数格式化。

If it is a round number, omit the decimal part. Otherwise format with two decimal places.

推荐答案

我对此表示怀疑。问题是如果它是浮点数100则永远不是100,它通常是99.9999999999或100.0000001或类似的东西。

I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.

如果你想以这种方式格式化,你必须定义一个epsilon,即与整数之间的最大距离,如果差异则使用整数格式较小,否则浮动。

If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.

这样的事情可以解决问题:

Something like this would do the trick:

public String formatDecimal(float number) {
  float epsilon = 0.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}

这篇关于Java货币编号格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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