# Thread: Floats and Doubles and Currency

1. Member Join Date
Feb 2014
Posts
20
Rep Power
0

## Floats and Doubles and Currency

Hi guys,

Just done a quick test to try and figure out the difference between floats and doubles.

I made a quick program which outputs the result of 3.3 * 2 as both a float and a double.

I assumed since a float is the larger and more precise of the two data types that there would be more numbers after the decimal point, however this was not the case, it was in fact the double which had more numbers after the decimal point. Result was as follows:

Float: 29.699999
Double: 29.7

BTW for the above code I simply had a few text fields and a button with the following code:
Java Code:
``` textBox3.setText("" +  Float.parseFloat(textBox1.getText())  * Float.parseFloat(textBox2.getText()));
textBox6.setText("" +  Double.parseDouble(textBox1.getText())  * Double.parseDouble(textBox2.getText()));```
I was just wondering if anyone could explain why this was the case?

Also, as these are limited to a certain amount of numbers im thinking there must be a more precise way for currency, if so what would I use for that?

I suppose what im trying to figure out is what data type to use in different scenarios? When to use integer, float, double and long.

Thanks in advance for any help I may get.  Reply With Quote

2. ## Re: Floats and Doubles and Currency

A float uses 32 bits for its mantissa and exponent, while a double uses 64 bits; a double can store more decimals. Be very careful if floats or doubles have to represent money; for one thing, both can't exactly represent the simple fraction 1/10 (0.1). Better rescale your monetary units and do all your arithmetic in cents and use simple ints or longs. This also fails if you want to use fractions of cents. You have to use BigDecimals then ... Also read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic, it's a must read if you want to do some serious floating point stuff.

kind regards,

Jos  Reply With Quote

3. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: Floats and Doubles and Currency

In fact, the only fractions that can be accurately represented in floating point are those whose denominators are only powers of two. This is analogous to decimal where the terminating (i.e. non-repeating) fraction's denominator must consist only of powers of two and five (the two prime factors if 10).

Regards,
Jim  Reply With Quote

4. Member Join Date
Feb 2014
Posts
20
Rep Power
0

## Re: Floats and Doubles and Currency

Thanks for the response guys, appreciate it.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•