java - 美元和美分计数器

标签 java currency

所以我接到了一项任务,要编写一个计数器,将给定量的美元和美分加在一起。我们获得了一个用于测试功能的测试类。

我们得到了以下提示:

public int dollars () //The dollar count. 
ensure: this.dollars () >= 0

public int cents () //The cents count. 
ensure: 0 <= this.cents() && this.cents() <= 99

还有:

public void add (int dollars, int cents) //Add the specified dollars and cents to this Counter. 
public void reset () //Reset this Counter to 0. 
ensure: this .dollars() == 0 && this.cents() == 0 

这是我当前的代码:

public class Counter {

    private float count;

    public Counter() {
        count = 0;
    }

    public int dollars() {
        if (this.dollars() >= 0) {
            count = count + Float.parseFloat(this.dollars() + "." + 0);
        } return 0;
    }

    public int cents() {
        if (0 <= this.cents() && this.cents() <= 99) {
            count = count + Float.parseFloat(+0 + "." + this.cents());
        } else if (100 <= this.cents()) {
            count = count + Float.parseFloat(+1 + "." + (this.cents() - 100));
        }
        return 0;
    }

    public void add(int dollars, int cents) {
        dollars = this.dollars();
        cents = this.cents();
    }

    public void reset() {
        count = 0;  
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

我意识到我在这里犯了错误(据说是在 float 中并试图计算 float 的美元和美分部分)。但我无法准确指出它失败的地方。

最佳答案

public final class Counter {

    private int cents;

    public int dollars() {
        return cents / 100;
    }

    public int cents() {
        return cents;    // if you want to retrun all centes
        // return cents % 100;    // if you want to return cents less than dollar
    }

    public void add(int dollars, int cents) {
        this.cents = dollars * 100 + cents;
    }

    public void reset() {
        cents = 0;
    }
}

财务规划的一条非常重要的规则:切勿使用 float 资金作为柜台资金。你肯定很快就会遇到问题,甚至很快就会遇到问题。看我的例子,实际上你的计数器可以很容易地实现,只需将美分数量保存为 int (正如我所看到的,你没有部分美分)。

附注一招成就 future

假设您需要一个浮点值并支持对其进行所有标准数学运算,例如 +,-,/,*。例如。美元和整数美分(如您的示例中),并且您不能(或不想)使用 float 操作。你应该做什么?

只需将整数值中的两位低位数字保留为小数部分即可。让我们以价格 12 美元为例:

int price = 1200;    // 00 is reserverd for centes, , price is $12
price += 600;        // add $6, price is $18
price += 44;         // add $0.44, price is $18.55

int dollars = price / 100;   // retrieve total dollars - $18     
int cents = cents % 100;     // retrieve cents less than dollars - 44  

关于java - 美元和美分计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346008/

相关文章:

java - Hibernate删除的对象应该重新保存

java - 在Java中使用ThreadPoolExecutor时如何通过超时取消特定任务?

java正则表达式从最后2个斜杠之间的url路径中提取密码

java - 在java中支持新的印度货币符号

Javascript如何将数字的输出更改为带有2位小数的美国货币

ruby-on-rails - Ruby Money gem 的最佳舍入方法是什么?

java - 任意货币字符串 - 将所有部分分开?

numbers - 在 Twig 模板中格式化金钱

java - IssueFactory.getIssue() 创建一个 id == null 的问题

java - 给定一个 WSDL 文件,通过 Internet 使用 Web 服务的步骤是什么?