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

asked on

Batch File [Advanced]:DisplayNumber (Specify Unit)

Hi there,

This is the first of a series of questions in order to team improve the following batch file.

Cheers,
Rene

FEATURE TO BE ADDED:
Add a parm that allows to specify the desired units.  If the desired unit is not specified ("") the result will be as the provided script.

EXAMPLES:
CALL :DisplayNumber Number "1 234 567" "MB"  ---> 1.234 MB
CALL :DisplayNumber Number "123" "MB"  ---> 0.000123 MB
CALL :DisplayNumber Number "1 234 567" ""  ---> 1.234 MB

@ECHO OFF
SETLOCAL EnableDelayedExpansion

CALL :DisplayNumber Number "000 0123 456 789"
ECHO !Number!
ECHO.

FOR /L %%A in (0,1,2) DO FOR /L %%B in (9,-1,0) DO (
   SET Val=%%B!Val!
   CALL :DisplayNumber Number "!Val!"
   ECHO !Number!
)

PAUSE
EXIT

:DisplayNumber [1=Result Var Name] [Val] 
SETLOCAL
CALL :CleanNb Nb "%~2"
SET UnitNb=0
SET Unit=[UN-DEFINED UNIT]
   :DisplayNumber1
   IF defined Nb SET digit=%Nb:~-3%
   SET /a UnitNb+=1
   SET Result2=!Result1!
   SET Result1=!digit!

   IF DEFINED Result2 (SET Result=%Result1%.%Result2%) ELSE (SET Result=%Result1%)
   SET Nb=%Nb:~0,-3%
   
   IF DEFINED Nb GOTO DisplayNumber1

   FOR /F "tokens=%UnitNb% delims=," %%A IN ("B,KB,MB,GB,TB,PB,EB,ZB") DO SET Unit=%%A
   ENDLOCAL & SET %~1=%Result% %Unit%
   GOTO :eof


:CleanNb
IF "%~2" == "" SET %~1=0 & EXIT /b
SETLOCAL
SET Nb=%~2
SET Nb=%Nb: =%
   :CleanNb2
   IF "%Nb:~0,1%" EQU "0" (
      SET Nb=%Nb:~1%
      GOTO CleanNb2
   )
   ENDLOCAL&SET %~1=%Nb%
   EXIT /b

Open in new window

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

@Bill,

Wow!

You implemented all your suggestions in one shot!!!

Your script is amazing!!!

Thank you master Yoda :)

Cheers,
Rene
Avatar of ReneGe

ASKER

I'll close it tomorrow friday, just in case someone else is working on another cool approach.
Cheers
Avatar of Bill Prew
Bill Prew

Thanks Rene.

~bp