In this post, I am going to show you how to write a simple JavaScript program to convert Kilometers to Miles. The formula is very simple, just divide the kilometers value by 1.609 you will get the value of the miles.
Let’s write the same in a plain JavaScript:
1 2 3 4 |
var kms = 5 var miles = km / 1.609; console.log(miles); //value will be 3.1075 |
It is that simple to Convert Kilometer to Miles in JavaScript.
Let me give you an entire example script here for you with bootstrap 4 form:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!doctype html> <html lang="en"> <head> <title>JavaScript program to convert Kilometer to Miles</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row"> <div class="col"> <br> <h2>JavaScript program to convert Kilometer to Miles</h2> <br> <div class="form-group"> <label for="km"><h4>Kilometer</h4></label> <input type="number" min="0" value="1" id="km" class="form-control" placeholder="" aria-describedby="helpId"> <small id="helpId" class="text-muted">Enter in kilometers</small> </div> <div class="form-group"> <h5>Result:<span id="res"></span></h5> </div> <div class="form-group"> <button type="button" id="convert" class="btn btn-primary">Convert to Miles</button> </div> </div> </div> </div> <!-- JavaScript starts here --> <script> document.getElementById("convert").onclick = function() { var km = document.getElementById("km").value; var miles = km / 1.609; miles = miles.toFixed(4); document.getElementById("res").innerHTML = ' ' + miles + ' miles'; } </script> </body> </html> |
You can see the demo of the above script here: