Convert double number to 3 decimal places number in Java
Here, we will learn to convert double number to 3 decimal places number in Java. There are many different ways to do that. Here, I will show you 4 ways.
What is a Double number?
A double is a Java primitive. We use it to store double-precision 64 bits of float data. We use double so that the results of multiple iterations are accurate. Moreover, it is also used for the manipulation of large numbers.
The syntax for a double is as follows:
double variable = float_type_data;
I have provided 4 different ways of converting a double to a 3 place decimal number.
DecimalFormat Class
DecimalFormat is a subclass of NumberFormat which is used to format numbers in decimal.
We need to make an object of the DecimalFormat class and specify the required format. Finally, we have to print the given double number as the parameter of the format()
method to get the required answer.
I have provided the code below.
import java.text.*; import java.util.*; class CodeSpeedy { public static void main(String args[]) { Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); DecimalFormat df = new DecimalFormat("#.###"); System.out.println(df.format(d)); } }
Let us give an input of 123.2345212. The resultant output is given below:
123.235
There is another way of specifying the format. Instead of ‘#’ signs, we use ‘0’. By using this way, one can even specify the number of digits to be shown before the decimal.
class CodeSpeedy { public static void main(String args[]) { Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); DecimalFormat df = new DecimalFormat("00000.000"); System.out.println(df.format(d)); } }
For the same input as above, the output is:
00123.235
Math.round() Method
We use the java.lang.Math.round()
method to round a floating number to the required value.
The syntax is as follows:
double var = Math.round(double var2);
For converting a double to a 3 decimal number, we have to multiply the parameter with 1000.0 and then divide the whole with 1000.0.
Check out the code for this method.
import java.util.*; class dbl_3dec2{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); double rnd = Math.round(d*1000.0)/1000.0; System.out.println(rnd); } }
For the same input as the previous problems, we get this output.
123.235
The printf() Method
We use printf()
to print a string according to the specified format. We give the required format inside quotes and print it.
class dbl_codespeedy{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); System.out.printf("The double number as 3 place decimal number: %.3f \n",d); }
The output for the same input as earlier is given below.
123.235
I hope this post was useful.
Leave a Reply