Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Float value weirdness...

Mike Ottinger
Ranch Hand
Posts: 125
Hi Guys,

This prints out: 178493.40625! Where does the extra (wrong) precision come from?

Thanks.

Tony Morris
Ranch Hand
Posts: 1608
The extra (right ) precision comes from the fact that Java floating point types are IEEE754 floating-point types. To use the terminology of IEEE (if I remember erectly), a floating-point type is an "inexact representation of a real number".

On the topic, do you know of any banks whose account software uses floating-point types?

Mike Ottinger
Ranch Hand
Posts: 125
Thanks for the quick reply: the issue is this value is going to be displayed as currency, how am I to deal with it rounding up if all I know about the input is that it's decimal is .4? Do I need to write my own work around for forcing the value to round down?

Thanks.

marc weber
Sheriff
Posts: 11343
If you're dealing with currency, you should use BigDecimal instances rather than floating-point primitives.

Marilyn de Queiroz
Sheriff
Posts: 9067
12
or multiply by 100 and use ints until you get the final answer.

Layne Lund
Ranch Hand
Posts: 3061
Personally, I prefer Marilyn's suggestion. Assuming you are using dollars as the currency value, you can use an int to hold the number of cents instead. Then for the final output divide by 100 to get the dollar amount and use the % operator to get the decimal amount.

I hope this description is clear enough, but if you still need help, don't be afraid to post some code so we can help you further.

Layne

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by Layne Lund:
Personally, I prefer Marilyn's suggestion.

Agreed - unless you have to work with fractions of cents, which many financial applications have to...

Mike Ottinger
Ranch Hand
Posts: 125
Hi Folks,

Thanks for all the answers. The context for this question was as such; I was retrieving this numneric value from a bean with a property of type float. I was then throwing it into a jstl fmt tag to get the proper format. This is where I was getting the unpredictable results. So I switched the type of the bean property from float to String and this worked. Thanks.

- M

marc weber
Sheriff
Posts: 11343
Originally posted by Ilja Preuss:
... unless you have to work with fractions of cents, which many financial applications have to...

Yes, this is the context I was coming from. The financial calculations I've worked with are not simple dollars and cents, but involve intermediate steps requiring up to 15 digits to the right of the decimal.

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.