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.
Example:
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
Java
import java.io.*;
class GFG {
static void change( double value, int decimalpoint)
{
value = value * Math.pow( 10 , decimalpoint);
value = Math.floor(value);
value = value / Math.pow( 10 , decimalpoint);
System.out.println(value);
return ;
}
public static void main(String[] args)
{
double firstvalue = 1212.12131131 ;
int decimalpoint = 4 ;
change(firstvalue, decimalpoint);
double secondvalue = 3.142857142857143 ;
int decimalpoint2 = 3 ;
change(secondvalue, decimalpoint2);
}
}
|
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
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
double firstvalue = 1212.12131131 ;
int decimalpoint = 6 ;
String temp_value = "" + firstvalue;
String string_value = "" ;
int counter = - 1 ;
for ( int i = 0 ; i < temp_value.length(); ++i) {
if (counter > decimalpoint) {
break ;
}
else
if (temp_value.charAt(i) == '.' ) {
counter = 1 ;
}
else if (counter >= 1 ) {
++counter;
}
string_value += temp_value.charAt(i);
}
double new_value = Double.parseDouble(string_value);
System.out.println(new_value);
}
}
|
Last Updated :
15 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...