If you need to truncate or to round floating point numbers you should always use functions from your compiler’s math library. These functions have been thoroughly tested and there is no reason why you want to implement such algorithms manually — except you are the one who is being asked to design a math library.

Nevertheless, you might be interested in the principle behind these functions. There are a many websites explaining the nuts and bolts of various algorithms that can be used for rounding up, rounding down, rounding to the nearest, etc. You will notice that it is not difficult to understand such algorithms since they just require some basic knowledge about numbering systems.

This was supposed to become a short posting, so I will focus only on two basic examples.

### Truncating

Given that *a* is a floating point number which is to be truncated to the third decimal digit. *b* is the variable to contain the truncated number (result). The following line of code will do the job.

int b = ((int) ( a * 1000.0 )) / 1000.0;

*a* is multiplied by 10³, because this will “shift” the decimal point three digits to the right. By this way the third digit right of the decimal point will become the first digit left of the decimal point.

Example: 3.14159265 * 1000 = 3141.59265

In the next step we need to cast the number to integer which truncates all digits right of the decimal point.

Example: (int) 3141.59265 = 3141

You got it … A floating point division that reverses the previous multiplication will do the rest.

### Rounding

Rounding follows exactly the same principle as shown above. The difference is that prior to truncation a number is added, which increments the least significant digit of the result if the digit right to the least significant digit is greater than or equal to 5. If we add 0.0005, for example, the 10⁻³ weighted digit will be incremented if the 10⁻⁴ weighted digit is greater than 0.0005.

a = a + 0.0005; int b = ((int) ( a * 1000.0 )) / 1000.0;

Simple math, isn’t it?

Cheers,

Andre M. Maier