Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Converting km per hour to cm per second using JavaScript
We are required to write a JavaScript function that takes in a number that specifies speed in kmph and it should return the equivalent speed in cm/s.
Understanding the Conversion
To convert km/h to cm/s, we need to understand the relationship:
- 1 kilometer = 100,000 centimeters
- 1 hour = 3,600 seconds
- Formula: km/h × (100,000 cm / 1 km) × (1 hour / 3,600 seconds)
Example
Following is the code:
const kmph = 12;
const convertSpeed = (kmph) => {
const secsInHour = 3600;
const centimetersInKilometers = 100000;
const speed = Math.floor((kmph * centimetersInKilometers) / secsInHour);
return `Equivalent in cm/s is: ${speed}`;
};
console.log(convertSpeed(kmph));
Equivalent in cm/s is: 333
More Precise Conversion
For better accuracy, we can return the decimal value instead of using Math.floor():
const convertSpeedPrecise = (kmph) => {
const secsInHour = 3600;
const centimetersInKilometers = 100000;
const speed = (kmph * centimetersInKilometers) / secsInHour;
return parseFloat(speed.toFixed(2));
};
console.log(convertSpeedPrecise(12)); // 12 km/h
console.log(convertSpeedPrecise(36)); // 36 km/h
console.log(convertSpeedPrecise(5.5)); // 5.5 km/h
333.33 1000 152.78
Simplified One-Line Function
We can also create a more concise version:
const kmphToCmps = (kmph) => (kmph * 100000) / 3600; console.log(kmphToCmps(18)); // 18 km/h to cm/s console.log(kmphToCmps(72)); // 72 km/h to cm/s
500 2000
Verification
Let's verify our conversion with a known example:
// 36 km/h should equal 1000 cm/s
const speed = 36;
const result = (speed * 100000) / 3600;
console.log(`${speed} km/h = ${result} cm/s`);
36 km/h = 1000 cm/s
Conclusion
Converting km/h to cm/s involves multiplying by 100,000 (cm per km) and dividing by 3,600 (seconds per hour). The simplified formula is: cm/s = km/h × (100,000 ÷ 3,600).
Advertisements
