We help IT Professionals succeed at work.

Batch File [Advanced]:DisplayNumber (Specify Unit)

562 Views
Last Modified: 2012-02-17
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

Comment
Watch Question

Test your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
@Bill,

Wow!

You implemented all your suggestions in one shot!!!

Your script is amazing!!!

Thank you master Yoda :)

Cheers,
Rene

Author

Commented:
I'll close it tomorrow friday, just in case someone else is working on another cool approach.
Cheers
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Thanks Rene.

~bp
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.