Link to home
Start Free TrialLog in
Avatar of ReneGe
ReneGeFlag for Canada

asked on

Batch File: Convert bytes to either KB, MB or GB with 2 decimal points

Hi there,

I need to create a batch file that will convert a number in bytes to either KB, MB or GB with 2 decimal points.

@echo off

FOR %%A IN (4321,1342.56,2145386496) do (
   call :ConvertNumber
   ECHO "%%A" is easyer to read like this: %ConvertedNumber%
)
ECHO.
PAUSE
EXIT

:ConvertNumber
whatever script
exit /b

RESULT:
4.21 KB
1.99 GB


Hoping this will be easy points for you.

Cheers,
Rene
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ReneGe

ASKER

Thanks billprew,

Cool, this is very educational.

Thanks,
Rene
Avatar of Bill Prew
Bill Prew

Here are a couple of the tools I use from time to time.  Best to rename CALC to something else, since calc.exe is now the Windows GUI calculator.

~bp
utils.zip
Avatar of ReneGe

ASKER

Thanks pal!

Rene
Avatar of ReneGe

ASKER

Just sharing a related simple script I just did.

Cheers,
Rene
@echo off
setlocal enabledelayedexpansion

for %%A IN (1,1024,1048576,1073741824) do (
	SET FileSize=%%A
	CALL :ConvertFileSize
	echo %%A Bytes=!FileSize!
	)
PAUSE
exit

:ConvertFileSize
IF !FileSize! GEQ 1073741824 (SET /a FileSize=!FileSize! / 1073741824 && SET FileSize=!FileSize! GB && Exit/b)
IF !FileSize! GEQ 1048576 (SET /a FileSize=!FileSize! / 1048576 && SET FileSize=!FileSize! MB && Exit/b)
IF !FileSize! GEQ 1024 (SET /a FileSize=!FileSize! / 1024 && SET FileSize=!FileSize! KB && Exit/b)
IF !FileSize! LSS 1024 SET FileSize=!FileSize! Bytes
exit /b

Open in new window

Just to show how the mathematician in me might approach it...

~bp
@echo off
setlocal enabledelayedexpansion
 
for %%A IN (1,1024,1048576,1073741824) do (
        SET FileSize=%%A
        CALL :ConvertFileSize
        echo %%A Bytes=!FileSize!
        )
PAUSE
 
for %%A IN (1,1024,1048576,1073741824) do (
        CALL :ScaleNumber %%A "FileSize"
        echo %%A Bytes=!FileSize!
        )
PAUSE
exit /b
 
:ConvertFileSize
IF !FileSize! GEQ 1073741824 (SET /a FileSize=!FileSize! / 1073741824 && SET FileSize=!FileSize! GB && Exit/b)
IF !FileSize! GEQ 1048576 (SET /a FileSize=!FileSize! / 1048576 && SET FileSize=!FileSize! MB && Exit/b)
IF !FileSize! GEQ 1024 (SET /a FileSize=!FileSize! / 1024 && SET FileSize=!FileSize! KB && Exit/b)
IF !FileSize! LSS 1024 SET FileSize=!FileSize! Bytes
exit /b
 
:ScaleNumber [input-number] [output-variable-name]
  set Number=%~1
  set Scale=1
  for /L %%A in (1,1,3) do (
    if !Number! GEQ 1024 (
      set /A "Number = Number >> 10"
      set /A Scale += 1
    )
  )
  for /F "tokens=%Scale% delims=," %%A in ("Bytes,KB,MB,GB") do set %~2=%Number% %%A
  exit /b

Open in new window

Avatar of ReneGe

ASKER

bp,

Your just too cool!!

Cheers,
Rene