...

/

Floating-Point and Character Types

Floating-Point and Character Types

Let's learn about floating-point and character types.

We'll cover the following...

Floating-point types

Not all numerical values are integers, so we’ll now take a look at another group of numerical data types, floating-point types. Representing floating-point numbers using binary format is tricky, and as a programmer, we soon discover some oddities that relate to this. Let’s take look at the following code:

result = 0.1 + 0.2

We would expect the result stored in the variable result to be 0.3, but in many languages, this will instead be something like 0.30000000000000004.

The reason we get odd results like this is because we try to represent a decimal floating-point number as a binary floating-point number. We won’t go into too much detail about how floating-point numbers are represented in a computer because it will get a bit complicated. If you want to learn how this is done, you can search for it online and see lots of detailed explanations of how it works. But what we’ll do is think about the problem the computer faces when dealing with a binary representation of a decimal number.

In our decimal positional system, each position in a number has a value, as we saw earlier. This is just as true for floating-point numbers as it is for integers. For a floating-point number, the positions ...