Skip to content

How to Round a Number to a Specific Decimal Place in Batch Script

Learn how to round numbers in Windows Batch scripts using PowerShell's [Math]::Round() for precise decimal control or a scaled integer workaround for pure Batch solutions.

Rounding is a fundamental operation in data processing, whether you need to display a percentage as 85.7% instead of 85.714285%, or format a price as $19.99. Since Batch only supports integer arithmetic, rounding to a specific decimal place requires either a Scaled Integer workaround or a PowerShell Bridge for true decimal support.

In this guide, we will demonstrate both approaches.

PowerShell provides the [Math]::Round() method for precise rounding.

Implementation Script

@echo off
setlocal

:: Round 85.714285 to 2 decimal places
for /f "usebackq delims=" %%A in (`
    powershell -NoProfile -Command "[Math]::Round(85.714285, 2)"
`) do set "result=%%A"

echo Rounded: %result%
pause

Dynamic Input

@echo off
setlocal

set "number=123.456789"
set "places=3"

for /f "usebackq delims=" %%A in (`
    powershell -NoProfile -Command "[Math]::Round(%number%, %places%)"
`) do set "result=%%A"

echo.
echo ==========================================
echo ORIGINAL: %number%
echo ROUNDED:  %result% (to %places% decimal places^)
echo ==========================================
pause

Method 2: Scaled Integer (Pure Batch)

If PowerShell is not available, you can simulate rounding by working in "Scaled Integers". To get one decimal place, multiply by 10; for two decimal places, multiply by 100.

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: Simulate: 100 / 3 = 33.33 (display to 1 decimal place)
set "numerator=100"
set "denominator=3"

:: Scale by 100 for rounding, then extract 1 decimal place
:: Add half the denominator before dividing to achieve rounding
set /a "scaled=(numerator * 100 + denominator / 2) / denominator"

:: Extract whole and fractional parts (scaled has 2 extra digits)
set /a "whole=scaled / 10"
set /a "decimal=scaled %% 10"

echo !numerator! / !denominator! = !whole!.!decimal! (rounded to 1 decimal place^)
pause

Why Round Numbers?

  1. User-Facing Reports: Displaying CPU Usage: 87.5%% is cleaner than 87.4999999%%.
  2. Financial Calculations: Prices, taxes, and invoices must be rounded to 2 decimal places.
  3. Scientific Data: Sensor readings or statistical results often need to be presented at a specific precision level.

Important Considerations

Conclusion

Rounding numbers to a specific decimal place is essential for producing clean, professional output. While Batch's integer-only math limits native capabilities, the PowerShell bridge provides full decimal precision with any rounding mode you need. By combining the speed of Batch scripting with the mathematical power of PowerShell, you build tools that present data with the exact level of precision your users expect.

Navigation