Convert Miles to Kilometers with JavaScript

At the end of the post you can view the working example. This example comes from Problem Solving, Abstraction, and Design using C++ (Third Edition) As a reminder, here are the steps to the Software Development Method
  1. Specify the Problem Requirements
  2. Analyze the problem.
  3. Design the algorithm to solve the problem.
  4. Implement the algorithm.
  5. Test and verify the completed program.
  6. Maintain and Update the Program.

1. Specify the Problem Requirements

Your summer surveying job requires you to study some maps that give distances in kilometers and some that use miles. You and your co-workers prefer to deal in metric measurements. Write a program that performs the necessary conversion, rounded to 2 decimal places.

2.Analyze the Problem

Given user input of the value of miles, display the conversion of miles to kilometers. Data Requirements
Problem Constants:
MILES_TO_KM = 1.609;   //Conversion constant for Miles to Kilometers
Problem Input miles; //The Distance in Miles Constraints on problem Input miles >= 0; miles is a number Problem Output km; //The distance in kilometers Relevant Formula 1 Mile = 1.609 Kilometers

3. Design the Algorithm

  1. Read in Distance in Miles
  2. Convert the distance in miles to distance in kilometers
      The distance in kilometers is 1.609 times the distance in miles
  3. Round the Distance in Kilometers to 2 Decimal Places
  4. Display the Distance in Kilometers

4.Implement the algorithm

Program language options:
  1. PHP
  2. Javascript
Program Language choice: Javascript Justification: No critical data must be passed to the server, so using Javascript will not pose any security risks in this situation. Although PHP could report the same output correctly, it would hinder the user experience by forcing the user to wait for a page refresh every calculation. View the Program in action

5. Test and verify the completed program

Test Data(Done by manual calculation): 20 Miles = 32.18 Kilometers 0 miles = 0 Kilometers 15 Miles = 24.14 Kilometers 37 Miles = 59.53 Kilometers 113 Miles = 181.82 Kilometers.

6. Maintain and Update the Program

At this point maintenance is currently not needed, but could be easily performed. In the event that standards change, such as the miles to km conversion rate, the program will need very little adjusting in order to function properly. View the Program February 07, 2010
About the Author:

Joseph is the lead developer of Vert Studios Follow Joseph on Twitter: @Joe_Query
Subscribe to the blog: RSS
Visit Joseph's site: joequery.me