T3RRYT3RR0R

FormatNum

Jul 30th, 2021 (edited)
873
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @Echo off
  2.  
  3. :# FormatNum function by T3RRY ; Created: 25th July 2021
  4. :# Purpose: Function to Format numbers up to 1485 digits long with coma's IE:
  5. :#  10 = 10 ; 100 = 100 ; 1000 = 1,000 ; 10000 = 10,000 ; 100000 = 100,000 ; 1000000 = 1,000,000
  6. :# -S and -0 switches accepted as third arg to prepend with whitespice or leading zero's respectively.
  7.  
  8.  Setlocal EnableExtensions
  9.  %= Examples =%
  10.  
  11. :# 0 prefixed
  12.  Call :FormatNum 1532151544621668007951135446231798748995413134278463598153468247 rv[1]1 -0
  13.  Call :FormatNum 4071 rv[1]2 -0
  14.  Call :FormatNum 20 rv[1]3 -0
  15.  Call :FormatNum 3 rv[1]4 -0
  16.  Set rv[1]
  17.  
  18. :# Whitespace prefixed
  19.  Call :FormatNum 1532151544621668007951135446231798748995413134278463598153468247 rv[2]1 -S
  20.  Call :FormatNum 4071 rv[2]2 -S
  21.  Call :FormatNum 20 rv[2]3 -S
  22.  Call :FormatNum 3 rv[3]4 -S
  23.  Set rv[2]
  24.  
  25. :# No Prefix
  26.  Call :FormatNum 1532151544621668007951135446231798748995413134278463598153468247 rv[3]1
  27.  Call :FormatNum 4071 rv[3]2
  28.  Call :FormatNum 20 rv[3]3
  29.  Call :FormatNum 3 rv[3]4
  30.  Set rv[3]
  31.  
  32. Endlocal
  33. Goto :Eof
  34.  
  35. :FormatNum <Int> <ReturnVar> [-0|-S]
  36.  If not defined FormatDelim Set "FormatDelim=," %= Allow default ',' delim to be overridden =%
  37.  If /I "%~2"=="-0" Exit /b 3 %= Errorlevel 3 - arg2 incorrectly occuipied by arg3 =%
  38.  If /I "%~2"=="-S" Exit /b 3
  39.  If "%~2"=="" Exit /b 2      %= Errorlevel 2 - arg2 missing =%
  40.  If "%~1"=="" Exit /b 1      %= Errorlevel 1 - all args missing =%
  41.  
  42. Setlocal EnableDelayedExpansion
  43.  set "tmp=.%~1" %= No Leading zeros =%
  44.  If "%~3"=="-0" set "tmp=.00%~1" %= Leading zeros =%
  45.  If /I "%~3"=="-S" set "tmp=.  %~1" %= Leading whitespace =%
  46.  
  47.  %= Approximate Max string length as a multiple of 3 to reduce execution time =%
  48.  For %%i in (1485 918 567 351 216 135 81 54 27 18 9)Do If "!tmp:~%%i,1!"=="" ( Set /A "Max=%%i" )
  49.  
  50.  For /l %%n in (!Max! -3 0)Do (
  51.   For /f "Delims=" %%o in ('Set /A %%n+3')Do If not "%%n"=="0" (
  52.    set "Size=!Size!%FormatDelim%!tmp:~-%%o,-%%n!"
  53.   )Else  set "Size=!Size!%FormatDelim%!tmp:~-3!"
  54.  )
  55.  
  56.  %= iterations below are required to remove all paired comas. =%
  57.  For /l %%i in (0 1 8)Do set "Size=!Size:%FormatDelim%%FormatDelim%=%FormatDelim%!"
  58.  %= remove excess leading chars =%
  59.  set "Size=!Size:~1!"
  60.  set "Size=!Size:.00%FormatDelim%=!"
  61.  set "Size=!Size:.0%FormatDelim%=!"
  62.  set "Size=!Size:.  %FormatDelim%=!"
  63.  set "Size=!Size:. %FormatDelim%=!"
  64.  set "Size=!Size:.%FormatDelim%=!"
  65.  set "Size=!Size:.=!"
  66. Endlocal & Set "%~2=%Size%"
  67. Exit /B 0
  68.  
RAW Paste Data