Many people tend to confuse two different concepts: truncation and rounding. However, and even though they may be sometimes related, they are different. So, today, we decided to take a closer look at each one.
Truncation Vs. Rounding
One of the things that you can see when you’re comparing truncation vs. rounding is that:
- Rounding a number in the range [2.5, 3.5) returns the number 3
- Truncating a number in the range [3.0, 4.0) returns the number 3
It’s important to keep in mind that while a square bracket ‘[‘ denotes inclusion in the range, a parenthesis ‘(‘ denotes non-inclusion in the range. So, this means that in [3.0, 4.0), this is the range of all numbers between 3 and 4, including 3 but not including 4.
What Is Truncation
Simply put, truncation means to chop off the decimal portion of a number. This means:
- Truncating 3.3 returns 3
- Truncating 3.8 returns 3.
But this is very easy to do manually. However, if you want to do it on your computer, the algorithm differs slightly depending on whether you are truncating a positive value (greater than or equal to zero) or a negative value (less than zero).
To ensure that we maintain things as simple as possible, let’s just take a look at the algorithm for truncating positive numbers.
Notice that the domains on the truncation function and round function for any given return value are offset by exactly 0.5. So, if you had a value that would truncate to 5 (say 5.75, for example), you could simply subtract 0.5 from the value, and your new value (5.25 in the example) would round to 5.
So, an easy way to truncate a positive value is to simply subtract 0.5 from it and then round it.
Using The Java Code
We understand that you may want to do this in Java. So, let’s see how you can easily do as well.
Since the Math.round method accepts a float value as an argument, this entire algorithm can be performed in a single step:
truncated = Math.round(nontruncated – 0.5f);
Please note that the above line of code has some specific notation:
- The round method is a static method in the class Math. Therefore, anytime you wish to call that method, the method name must be proceeded by the class name (ie: Math.round)
- Check the Java Class Documentation to see what type of values Math.round will accept as an argument and what types of values it will return. You will see that, if nontruncated is a float value, then Math.round will return an int. As such, truncated must be declared of type int.
- Note that when you subtract 0.5, you actually write it as 0.5f. This is because Java treats any decimal constant you write into your code as type double by default, and you must include a trailing ‘f’ if you wish the number to be treated as type float.