Floating point variables can hold real numbers, i.e. ones with a fractional part. Some numbers with fractions cannot be held accurately, for example the value of pi has been computed to several million decimal places but we still don't know its exact number.

When a computer holds a floating point number it holds it to a particular precision (how many digits we can hold?) and a particular range (what is the largest number we can hold?). Different versions of C work to different levels of precision, and you can look these up in the manual for the C you are using.

There are one or two special issues which you must remember when you use floating point numbers:

  • You should never compare two floating point numbers to see if they are equal because the fact that we can't hold such numbers exactly may cause your program to do the wrong thing. (i.e. one variable may hold 1.0 and the other 0.99999999 - in which case C would decide they are different numbers)

  • When you transfer a floating point number into an integer the fractional part is thrown away, it is not rounded up. We will look at issues of number truncation later on.

  • When you do arithmetic between integers you do not get floating point answers, i.e. 7/2 would work out to 3, not 3.5

You declare floating point numbers by using the float keyword:

float average ; /* average weight */

The BoostC help does not mention floating point values at all because they are not implemented by the compiler. This is quite reasonable since the PICmicro microcontroller has neither the speed nor the space to perform floating point work.

The average floating point library would more than fill the memory of the PICmicro microcontroller! In any case, the applications we will be using the PICmicro microcontroller for will be more concerned with simple control and input/output than complex calculations.

Using Scaled Integers

In the program on the right I have solved the problem by holding a length value in 10ths of a mm. If I do this kind of thing I must make sure that I am never going to have a length value greater than the largest integer, and that I use plenty of comments to tell other programmers what I am doing.