programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Wrapper class Double

Duc Ta
Ranch Hand
Posts: 46
2
Hi everyone,
I have a question about Wrapper class Double
I initialized a Double object by using float parameter: 30.3f like the code below:

Then, I printed out
The output is:
Double: 30.299999237060547

Can anyone explain why the output is not 30.3

Carey Brown
Saloon Keeper
Posts: 3323
46
• 1
What your seeing is the binary approximation of 30.3 because 30.3 cannot be represented precisely in binary.

If you are just trying to print it then try
Where the '1' says how many decimal places you want to show.

If you need it to be precise and it's not just a print issue, then use BigDecimal instead of Double.

Carey Brown
Saloon Keeper
Posts: 3323
46
Note that your "30.3f" is a float type and not a double. Floats are almost never used and when they are it is usually to be compatible with some legacy code.

If you just used "30.3" (with a decimal place) then it will be a type of double.

Summary: use doubles.

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Note that your question has nothing to do with the wrapper class Double specifically. If you would have used the primitive type double, you would have had exactly the same problem.

Campbell Ritchie
Marshal
Posts: 56545
172
Carey Brown wrote:. . . use BigDecimal instead of Double.
But don't use this constructor.

Daniel Cox
Ranch Hand
Posts: 231
12
The JLS says that a widening primitive conversion from float to double may result in "loss of information."

A widening primitive conversion from float to double that is not strictfp may lose information about the overall magnitude of the converted value.

Campbell Ritchie
Marshal
Posts: 56545
172
• 1
What may happen if you are not in a strictfp context is that a float is expanded to occupy > 32 bits, maybe 48 or 64. The rightmost bits are used to enhance the precision of the calculations, but the cast will reduce the float to a 32‑bit number and any other bits will be lost; when the number undergoes widening conversion to a double, those rightmost bits are replaced by 0000...

The correct approach (I think) is to note what CB says and don't use floats unless some method forces you to.

 It is sorta covered in the JavaRanch Style Guide.