Reputation: 149
As part of a larger program, I have this function that, when called, returns the string under return. accountHolder, balance, interestRate, and points are variables in an object of type RewardsCreditAccount. So, for example, I declare an object here:
RewardsCreditAccount testAccount = new RewardsCreditAccount("Joe F. Pyne", 7384.282343837483298347, 0.173, 567);
So this object will set accountHolder = "Joe F. Pyne", balance = 7384.282343837483298347, and so on.
In the function below, I return this information in a string that should look like this:
Joe F. Pyne, $7384.282, 17.28%, 567 points
Using this function:
public String toString() {
return (accountHolder + ", $" + + balance + 100*interestRate + "%, " + points + " points");
}
However, it is in fact returning this:
Joe F. Pyne, $7384.282, 17.299999999999997%, 567 points
I tried this, but to no avail
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
This is rather annoying, because I want it to only return two decimal places. I know this can be done using %1.2f, but I have no idea how to format the syntax for that. I would vastly appreciate any help on getting the decimal value to display properly. Thanks!
Upvotes: 2
Views: 8072
Reputation: 16059
You'll have to use String.format();
with that format-String.
So this
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
Should be:
public String toString() {
return String.format("%s, $%,1.2f %s%%, %s points", accountHolder, balance, 100*interestRate, points );
}
With the formatters set so that it is printed according to your desires.
Upvotes: 6
Reputation: 213203
You will need to use String.format()
to format your returned String: -
String.format("%5.2f",balance)
Upvotes: 4
Reputation: 20726
Floating point numbers are not always easy to deal with.
Your problem lies in the fact that floating point types (as float and double, and their boxed counterparts) are just binary approximations of their decimal representation, so all kinds of such problems can arise when not taking this into count.
You also have to pay attention when handling very large values, because it can occur that (a== (a+1))==true
...
Also, for currencies, and other such critical data, I'd recommend BigDecimal, which stores the exact string representation, not the binary approximation. That is not the most trivial thin on Earth to handle though, but given the criticality of data, I think it is unavoidable.
Upvotes: 1
Reputation: 41200
Use DecimalFormater for formatting your value.
new DecimalFormat("###.##").format(17.299999999999997);
For reference.
Upvotes: 5