Effective Java: Avoid Float and Double If Exact Answers Are Required

Kyle Carter
CodeX
Published in
3 min readJun 26, 2021

--

Photo by Jeswin Thomas on Unsplash

This chapter dives into a fun computer science based topic. When we have a need to represent numbers that include a decimal point we will often reach for either a float or a double. These primitive types facilitate the representations of approximate floating point values over various magnitudes. A key part of the previous sentence is that it's an approximation. We must not use floats or doubles when we need exact answers, especially when dealing with numbers.

Let’s briefly go over why this is the case. The goal of floating point types is to allow the representation of any number with any number of digits before or after the decimal point. Unfortunately
we aren’t able to represent any number but the goal is still there. With a float we have 32 bits to use to represent all of this. In order to accomplish this Java implements the IEEE 754 standard. This lays out the bits as follows. 1 bit for sign, 8 bits for the exponent, and 23 bits of mantissa. The way all these bits are used together is as follows for example for the number 1.23. The first bit being the sign denotes if the number is positive or negative. Next we will skip to the mantissa. Here we would represent the number 123. Finally our exponent portion will be used to represent 10-². Putting the sign of positive together with 123 * 10-². This format can indeed represent…

--

--

Kyle Carter
CodeX

I'm a software architect that has a passion for software design and sharing with those around me.