How to Truncate the Double Value to Given Decimal Places in Java?
In simplest terms, truncation means to chop off the decimal portion of a number. A method of approximating a decimal number by dropping all decimal places past a certain point without rounding.
Given a double value and a decimal place truncate the value to the given decimal point.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: val = 3.142857142857143 Decimal point = 3 Output = 3.142 Upto 3 decimal places
Approach 1: Using Mathematically :
- Shift the decimal of the given value to the given decimal point by multiplying 10^n
- Take the floor of the number and divide the number by 10^n
- The final value is the truncated value
Approach 2: Using String matching approach
- Convert the number into String
- Start the counter variable when “.” found in the String
- Increment the counter till decimal point
- Store the new String and parse it in double format