I'm doing a very simple operation. Here's the code:
float expectedTotal = 32.97;
float firstPrice = 7.99;
expectedTotal -= firstPrice;
When I assert that, expectedTotal should be 24.98, but I end up with an error saying:
expected [24.980001] but found [24.98]
So the first question would be: Where is this 0.000001 comes from?
I have read in other stackoverflow that dealing with currencies is not ideal with float and I should use the DecimalFormat. I tried with the following code:
DecimalFormat df = new DecimalFormat("#.##");
String s = String.valueOf(expectedTotal);
String newString = df.format(s);
expectedTotal = Float.valueOf(newString);
But receive the error:
java.lang.IllegalArgumentException: Cannot format given Object as a Number
I also tried with a parse:
DecimalFormat df = new DecimalFormat("#.##");
String s = df.format(expectedTotal);
try {
expectedTotal = (float) df.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
Basically, all I want is expectedTotal
as a float with only 2 decimals.
Anyone can help me please ?