J
Jacob
Hello everyone,
I am teaching Java for the first time this semester and I'm looking
for an explanation to a problem I have encountered. My students were
working with dollar amounts stored as floats and they needed to get
the whole dollar amount isolated from the change. I suggested they do
this:
float totalAmount,
wholeDollars,
change;
totalAmount = 5.08f;
wholeDollars = (int) totalAmount;
change = totalAmount - wholeDollars;
It seems that this would work leaving change to be 0.08 - but instead
change has the value 0.07999992 which cause some calculations to go
wrong later on. I understand that this has to do with casting the
float as an integer but I'm wondering what is actually going on (at
the bit level I guess?) that causes the result to come out this way?
Thanks,
Jacob
I am teaching Java for the first time this semester and I'm looking
for an explanation to a problem I have encountered. My students were
working with dollar amounts stored as floats and they needed to get
the whole dollar amount isolated from the change. I suggested they do
this:
float totalAmount,
wholeDollars,
change;
totalAmount = 5.08f;
wholeDollars = (int) totalAmount;
change = totalAmount - wholeDollars;
It seems that this would work leaving change to be 0.08 - but instead
change has the value 0.07999992 which cause some calculations to go
wrong later on. I understand that this has to do with casting the
float as an integer but I'm wondering what is actually going on (at
the bit level I guess?) that causes the result to come out this way?
Thanks,
Jacob