Truncating vs Rounding decimal numbers- The Difference
The first thing to notice is a pseudo-relation between rounding and truncating.
In simplest terms, truncation means to slice off the decimal portion of a number. This means:
- Truncating 3.3 returns 3
- Truncating 3.8 returns 3
What is rounding to two decimal places?
It is a process that returns the closest finite number expressed to two decimal places. This means:
- Rounding 3.465 to two decimal places returns 3.47
- Rounding 3.464 to two decimal places returns 3.46
[Recomended Reading: How to Round Numbers in SAS?]
Truncating decimal numbers in SAS without rounding
Sometimes it is necessary to truncate displayed numeric values to a specified number of decimal places without rounding.
For example, if we need to truncate 24536.8746 to 3 decimal places without rounding, the displayed number should be 24536.874 and not 24536.875. This is as compared to the rounded number, 24536.875).
For more information on rounding numbers in SAS, see our guide on How to Round Numbers in SAS?
If you think you can truncate numeric values by applying SAS w.d format, think again.
Try running this SAS code:
data test; x=24536.8746; y=x; format y 9.3; run;
The TRUNC function might come to your mind, and if you look at the SAS TRUNC function documentation, you will find that it does truncate numeric values. Rather it truncates to a specified number of bytes, which is not the same for numerics.
The TRUNC function truncates a numeric value to a smaller number of bytes, as specified in length and pads the truncated bytes with 0s.
How to Truncate Decimals in SAS?
So, to truncate decimals in SAS, we have a workaround to drop decimal places without rounding.
Let’s take the number 24536.8746 as an example, keeping only 3 digits after the decimal.
We can do it in 3 steps:
- Multiply the number by 103, effectively making the decimals part of a whole number.
- Then, apply the INT() function to truncate the decimal portion, keeping only the whole portion from the previous step.
- Divide the result of step 2 by 103. This will shift the decimal point 3 places to the left.
data test; number=24536.8746; step1=10**3; step2=int(number*step1); step3=step2/step1; run;
We hope this article helped you to truncate decimals in SAS. Moreover, if you have any other suggestions, suggest them below the comment section. We would take those lists in our further blog post.
Thanks for reading!
You may also want to see our article on the Length and Precision of SAS Variables.