Question

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.

Was it helpful?

Solution

A better way would be something like this for a general case:

format = "%d.%02d";

%02d gives you 0 padding for 2 digits. That way you don't need the extra if statement.

See this for more explanation of things you can do in format: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

OTHER TIPS

The modulus operator returns the remainder after division without fractional calculation. In this case, 4005%100 returns 5 as the remainder of 4005/100 is 5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top