Convert floating point variable to integer?

后端 未结 4 1286
粉色の甜心
粉色の甜心 2021-01-08 00:52

The shell script shown below will show a warning if the page takes more than 6 seconds to load. The problem is that the myduration variable is not an integer. H

4条回答
  •  情深已故
    2021-01-08 01:51

    It's not entirely clear, but I think you're asking how to convert a floating-point value (myduration) to an integer in bash. Something like this may help you, depending on which way you want to round your number.

    #!/bin/bash
    
    floor_val=
    ceil_val=
    
    function floor() {
        float_in=$1
        floor_val=${float_in/.*}
    }
    
    function ceiling() {
        float_in=$1
        ceil_val=${float_in/.*}
        ceil_val=$((ceil_val+1))
    }
    
    
    float_val=$1
    echo Passed in: $float_val
    floor $float_val
    ceiling $float_val
    
    echo Result of floor: $floor_val
    echo Result of ceiling: $ceil_val
    

    Example usage:

    $ ./int.sh 12.345
    Passed in: 12.345
    Result of floor: 12
    Result of ceiling: 13
    

提交回复
热议问题