Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
How to do truncation?
2.
Methods to perform truncation in Java
2.1.
Code
2.1.1.
Output
2.2.
Code
2.2.1.
Output
3.
Frequently Asked Questions
3.1.
What is the meaning of truncation in Java?  
3.2.
What is rounding off?
3.3.
How truncation in Java is different from rounding off?
3.4.
Does Java have large dependencies?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

What is truncation in Java?

Author Saksham Gupta
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Java is commonly asked in tech interviews, and thus it's important for us to study Java in detail. Out of all asked topics, Truncation in Java is one of the most asked topics.

In English, truncate means to trim or cut something. Truncation in Java programming refers to removing certain float or double-type digits or characters from the right of a string. We can also remove all of the decimal points that convert it to an integer. Keep in mind that the number won't be rounded to the nearest value after truncation. Truncation is a method of approximation of a result.

When division with integers is required, and the results must also be integers, it is frequently used in computing (particularly in databases and programming)

Introduction

Also See, Multithreading in java, and Duck Number in Java.

How to do truncation?

If you are truncating a positive value (greater than or equal to zero) or a negative value, the process will vary slightly (less than zero).

Let's just talk about the algorithm for truncating positive values to keep things simple (and the really motivated among you can see if you can figure out an algorithm for truncating negative numbers).

Keep in mind that for every given return value, the domains of the truncation function and round function are offset by precisely 0.5. Amazing, huh?

For example, if I had a number of 5.75 that would truncate to 5, I could simply remove 0.5 from it to get a new value of 5.25, which would round to 5. So, to truncate a positive value, just deduct 0.5 from it, round the result, and you're done.

Now let's perform truncation in Java.

Methods to perform truncation in Java

An array of single-dimensional arrays makes up a two-dimensional array in Java. A two-dimensional array will contain one set of columns for each one-dimensional array.

  • Mathematically
    • By multiplying 10^ n, move the decimal of the given number to the chosen decimal point.
    • Divide the amount by 10^n after taking the floor of the number. 
    • The truncated value is the final value.
Method 1

Let's see the implementation of the above method.

Code

import java.io.*;

class CodingNinjas {

	static void change(double num, int decimal)
	{


		// 10 ^ n.
		double dp=Math.pow(10, decimal);

		// Multiplying as told in step 1.
		num *=dp ;
		num = Math.floor(num);

		// Dividing.
		num = num / dp;
		
		System.out.println(num);
		
		return;
	}


	public static void main(String[] args)
	{

		double num1 = 132.692691;
		int decimal = 4;

		change(num1, decimal);

		num1 = 92.38953;
		decimal = 3;

		change(num1, decimal);
	}
}

Output

132.6926
92.389

Practice by yourself on java online compiler.

  • String matching approach
    • Firstly, we will change the given number to a string.
    • We will initialize the counter variable when the String contains "."
    • Now, The counter will be increased until the decimal point.
    • The new String will be saved and parsed in double format.

Let's see the implementation of the above

Code

import java.io.*;


class CodingNinjas {
	public static void main(String[] args)
	{
		double num = 132.692691;
		int decimal = 4;

	
		// Convert the number to string.
		String sv = "" + num;
		String val = "";

		int count = -1;
   
        int i=0;
        while(i<sv.length()) {

			// If crosses the decimal.
			if (count > decimal) {
				break;
			}
			else if (sv.charAt(i) == '.') {
				count = 1;
  			}
  			
			else if (count >= 1) {
				count++;
			}	


			// Number is converted to a string.
			val += sv.charAt(i);
			i++;
		}


		// Parsing and storing as double.
		double nv = Double.parseDouble(val);

		System.out.println(nv);
	}
}

Output

132.6926
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is the meaning of truncation in Java?  

In Java, Truncation is a method of removing certain float or double-type digits or characters from the right of a string. We can also remove all decimal points that convert it to an integer. Remember that the number won't be rounded to the nearest value after truncation. Truncation in Java is a method of approximation of results.

What is rounding off?

When a number is rounded off, its value is maintained but is brought closer to the next number, simplifying the number. For entire numbers as well as decimals at different places of hundreds, tens, tenths, etc., it is done. The crucial figures are preserved when numbers are rounded off.

How truncation in Java is different from rounding off?

Truncation is essentially the same as rounding a decimal value to the nearest whole number, with the exception that rounding off is done to 2 decimal places.

Does Java have large dependencies?

In order to have as few implementation dependencies as feasible, Java is a high-level, class-based, object-oriented programming language.

Conclusion

In this article, We talked about truncation in java. For more interesting and insightful articles like the truncation in java, Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. For placement preparations, look at the interview experiences and interview package.

You can also consider our paid courses  to give your career an edge over others!

Previous article
Static Data Structure vs Dynamic Data Structure
Next article
Delegation Event Model in Java
Live masterclass