What is truncation in Java?
The English meaning of truncate is to trim or prune, or cut something and the process of trimming is called truncation. In the computer science field, the term is often used in reference to data-types or variables (like String, floating-point numbers, etc.). It is a way of approximation. Let's discuss what is truncation in Java and how can we truncate a floating or double-type number through a Java program.
In Java programming, truncation means to trim some digits of a float or double-type number or some characters of a string from the right. We can also truncate the decimal portion completely that makes it an integer. Remember that after truncation, the number will not be round to its nearest value. Hence, truncation is a way of approximation.
It is usually used in computing (especially in database and programming) when division is done with integers and the results must be an integer.
Note: Truncation and rounding are two completely different concepts. It is not the same as Math.floor(), Math.ceil(), and Math.round() function of the Math class.
Now we have clearly understood the concept of truncation. Let's see some approaches to truncate floating or double-type numbers and string too.
Suppose, a double-type number num=19.87874548973101 is given. It is required that there must be only 3 digits after the decimal point. In such cases, we apply truncation. After truncating the rest digits, we get 19.878.
If we truncate all the digits coming after decimal-point, it becomes 19. If the number has been rounded to the nearest integer it becomes 20.
Now we have clearly understood truncation. Let's see some approaches to truncate floating or double-type numbers and string too.
There are two approaches to truncate a number:
Using Mathematical Logic
We can truncate the number by using the following steps:
The value that we get from step 3, is a truncated value.
If we represent the steps above in terms of math, we get:
Example: Truncate 1.231 up to 2 decimal places.
Let's implement the above logic in a Java program.
The number before truncation is: 19.87874548973101 The number after truncation is: 19.87874
Using String Matching
The value that we get from step 4, is a truncated value.
Let's implement the above steps in a Java program.
The number before truncation is: 556.9871233986399 The number after truncation is: 556.987
We can also trim a string in Java. For this Java String class provides the trim() method.