Batch rounding a number

后端 未结 5 661
滥情空心
滥情空心 2021-01-25 21:23

I have a script that calculates disk space in bytes. I have found a way to convert it to megabytes. I have just run it and i got a this: 1867.603187561035. Is there

5条回答
  •  野的像风
    2021-01-25 21:47

    @echo off
    set "number_to_round=1867.603187561035"
    
    for /f "tokens=1,2 delims=." %%a  in ("%number_to_round%") do (
      set first_part=%%a
      set second_part=%%b
    )
    
    set second_part=%second_part:~0,1%
    echo %second_part%
    if defined second_part if %second_part% GEQ 5 ( 
    
        set /a rounded=%first_part%+1
    ) else ( 
        set /a rounded=%first_part%
    )
    
    echo %rounded%
    

    OR (with the javascript call you can get more precise results and work with long number (while batch is limited to integers))

    @echo off
    set number_to_round=1867.603187561035
    
    set "beginJS=mshta "javascript:close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(Math.round(%number_to_round%)"
    set "endJS=));""
    
    for /f %%N in (
      '%beginJS%%endJS%'
    ) do set rounded=%%N
    
    echo %rounded%
    

提交回复
热议问题