Skip to content

How to Convert Kilometers to Miles and Vice Versa in Batch Script

Learn how to convert between kilometers and miles in Windows Batch scripts using scaled integer arithmetic for precise distance conversions without decimal support.

Unit conversion is a practical requirement for scripts that process geographic data, logistics reports, or hardware specifications from international sources. Converting between Kilometers and Miles requires a simple multiplication by a conversion factor. The challenge in Batch is handling this without decimal support, which requires a "Scaled Integer" approach.

In this guide, we will demonstrate how to perform both conversions with reasonable integer precision.

The Conversion Factors

  • Kilometers to Miles: Miles = Kilometers × 0.621371
  • Miles to Kilometers: Kilometers = Miles × 1.60934

Since Batch cannot use decimals, we multiply by a scaled integer and then divide:

  • Miles ≈ Kilometers × 621 / 1000
  • Kilometers ≈ Miles × 1609 / 1000

Implementation Script

@echo off
setlocal enabledelayedexpansion

:menu
cls
echo --- DISTANCE CONVERTER ---
echo 1. Kilometers to Miles
echo 2. Miles to Kilometers
echo 3. Exit
echo.
set /p "choice=Select an option: "

if "!choice!"=="1" goto :km2mi
if "!choice!"=="2" goto :mi2km
if "!choice!"=="3" exit /b
goto :menu

:km2mi
set /p "val=Enter Kilometers: "

:: Calculate whole and decimal parts separately
set /a "whole=val * 621371 / 1000000"
set /a "frac=(val * 621371 %% 1000000) / 10000"
if !frac! LSS 10 set "frac=0!frac!"

echo.
echo !val! km is approximately !whole!.!frac! miles.
pause
goto :menu

:mi2km
set /p "val=Enter Miles: "

:: Calculate whole and decimal parts separately
set /a "whole=val * 160934 / 100000"
set /a "frac=(val * 160934 %% 100000) / 1000"
if !frac! LSS 10 set "frac=0!frac!"

echo.
echo !val! miles is approximately !whole!.!frac! km.
pause
goto :menu

Why Convert Distance Units in Batch?

  1. International Reporting: If your organization has offices in both the US (Miles) and Europe (Kilometers), converting distances in logistics or delivery reports ensures consistency.
  2. Network Cabling: Converting between metric and imperial measurements for planning cable runs in international data centers.
  3. Geographic Calculations: Scripts that process GPS coordinate deltas often need to express distances in both units.

Important Limitations

PowerShell for Precision

@echo off
setlocal

set /p "km=Enter Kilometers: "

for /f "usebackq delims=" %%R in (`
    powershell -NoProfile -Command "[math]::Round(%km% * 0.621371, 2)"
`) do set "miles=%%R"

echo %km% km = %miles% miles
pause

Conclusion

Converting between kilometers and miles is a simple but practical tool for any script handling international data. While Batch's integer-only math introduces small rounding errors, the scaled-integer approach provides a reliable approximation. For applications requiring high precision, the PowerShell bridge fills the gap seamlessly.

Navigation