【问题标题】:Using integers for currency使用整数表示货币
【发布时间】:2012-05-31 12:55:50
【问题描述】:

我正在编写一个程序,使用 seam 和一个 SQL 数据库来存储有关员工的信息。有人告诉我将工资以整数形式存储在数据库中。当用户输入工资时,它被存储为一个字符串,当我为员工对象使用一个 setter 时,它把它变成一个 int。我的问题是我无法弄清楚如何将它存储回字符串中,并且小数点就位。有什么想法吗?

【问题讨论】:

  • int 应该是“美分数”,不是吗?
  • 是的。 int 是浮点数 * 100

标签: java int seam currency


【解决方案1】:

肯定一般来说最简单的事情可能是

BigDecimal.valueOf(cents).scaleByPowerOfTen(-2).toString();

(这具有概括为longBigInteger 美分数量的优势,在紧要关头。)

另一个肯定可行的解决方案,虽然稍微复杂一些,但类似于

return Integer.toString(cents / 100)
     + "."
     + new DecimalFormat("00").format(cents % 100);

【讨论】:

    【解决方案2】:

    如果存储为美分数,请将其格式化为float,然后除以 100。

    【讨论】:

    • 我会使用双精度(15 位精度)而不是浮点型(6 位精度)
    • 在货币计算中使用 float 或 double 是非常糟糕的主意,因为您可能会丢失精度!请阅读这篇关于这个问题的文章 - dzone.com/articles/…
    【解决方案3】:

    你可以使用类似的东西。

    int priceInCents = ...
    String price = String.format("%.2f", priceInCents / 100.0);
    

    【讨论】:

      【解决方案4】:

      您会寻找这样的东西吗?

      class Currency {
        int cents;
      
        public Currency(int cents) {
          this.cents = cents;
        }
      
        public Currency(String cents) {
          this(Integer.parseInt(cents));
        }
      
        public int getCents(){
          return cents;
        }
      
        public double getValue(){
          return cents/100.0d;
        }
      
        private static final DecimalFormat o = new DecimalFormat("0");
        private static final DecimalFormat oo = new DecimalFormat("00");
      
        @Override
        public String toString() {
          return o.format(cents / 100) + "." + oo.format(cents % 100);
        }
      }
      

      【讨论】:

      • 感谢大家的回复。我现在想通了。
      猜你喜欢
      • 2012-02-22
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多