2

I am doing a college assignment in Java that deals with currency. For that I am advised to use ints instead of doubles and then later convert it to a dollar value when I print out the statement.

Everything works fine until I do calculations on the number 4005 (as in $40.05 represented as an int). I am pasting the part of code I am having problems with, I would appreciate if someone could tell me what I am doing wrong.

import java.io.*;
class modumess {
    public static void main(String[] args) {
        int money = 4005; //Amount in cents, so $40.05;

        // Represent as normal currency
        System.out.printf("$%d.%d", money/100, money%100);
    }
}

The above code, when run, shows $40.5, instead of $40.05. What gives?

Kindly note that this is for my homework and I want to learn, so I would really appreciate an explanation about the root of the problem here rather than just a simple solution.

EDIT: Following Finbarr's answer, I have added the following to the code which seems to have fixed the problem:

if (money%100 < 10) {
            format = "$%d.0%d";
        }

Is this a good way to do it or am I over-complicating things here?

EDIT: I just want to make it clear that it was both Finbarr and Wes's answer that helped me, I accepted Wes's answer because it made it clearer for me on how to proceed.

4

2 回答 2

6

对于一般情况,更好的方法是这样的:

format = "%d.%02d";

%02d为您提供 2 位数字的 0 填充。这样你就不需要额外的 if 语句。

有关您可以按格式执行的操作的更多说明,请参阅此内容:http: //docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

于 2012-01-17T01:54:48.710 回答
2

模运算符返回除法后的余数,不进行小数计算。在这种情况下,4005%100 返回 5,因为 4005/100 的余数是 5。

于 2012-01-17T01:43:59.500 回答