Convert km to miles
In this article, we will take a look at km to miles conversion with java program that takes number of kilometers to be converted as user input.
The relation between km and miles is
1 mile = 1.60934 km
which means that there are 1.60934 km in a mile.
So, to convert km to miles, we need to divide the number of kilometers to be converted by 1.60934.
Formula to convert km to miles will be
1 km = 1/1.60934 miles
Java program
Below is a java program that reads the number of kilometers to convert to miles as user input using scanner class.
Then, it divides this value by 1.60934.
Finally, it formats the result to 4 decimal places.
Scanner scanner = new Scanner(System.in); System.out.println("Enter distance in km"); // read km input String kmDist = scanner.nextLine(); // convert km to miles double mileDist = Double.parseDouble(kmDist)/1.60934; NumberFormat format = new DecimalFormat("#.####"); System.out.println(kmDist + " km to miles is " + format.format(mileDist)); scanner.close();
Output is
Enter distance in km
5
5 km to miles is 3.1069
Above program converts 5 km to miles.
Note that nextLine()
reads user input as a string. So, we need to convert it to a double
value using Double.parseDouble()
.
We can also use nextDouble()
method of scanner to directly read a double
value as shown below
Scanner scanner = new Scanner(System.in); System.out.println("Enter distance in km"); // read km input double kmDist = scanner.nextDouble(); // convert km to miles double mileDist = kmDist/1.60934; NumberFormat format = new DecimalFormat("#.####"); System.out.println(kmDist + " km to miles is " + format.format(mileDist)); scanner.close();
Output is
Enter distance in km
10
10.0 km to miles is 6.2137
It successfully converts 10 km to miles.