【问题标题】:Rounding up float point numbers bash四舍五入浮点数bash
【发布时间】:2014-10-20 12:15:22
【问题描述】:

好的,所以我正在尝试对 17.92857 的输入进行四舍五入,以便在 bash 中获得 17.929 的输入。

到目前为止我的代码是:

read input
echo "scale = 3; $input" | bc -l

但是,当我使用它时,它不会四舍五入,而是返回 17.928。

有人知道解决办法吗?

【问题讨论】:

标签: bash shell floating-point decimal rounding


【解决方案1】:

如果input 包含数字,则不需要像bc 这样的外部命令。你可以用printf:

printf "%.3f\n" "$input"

编辑:如果输入是公式,您应该使用bc,如以下命令之一:

printf "%.3f\n" $(bc -l <<< "$input")
printf "%.3f\n" $(echo "$input" | bc -l)

【讨论】:

    【解决方案2】:

    要扩展 Tim 的答案,您可以为此编写一个 shell 辅助函数 round ${FLOAT} ${PRECISION}:

    #!/usr/bin/env bash
    
    round() {
      printf "%.${2}f" "${1}"
    }
    
    PI=3.14159
    
    round ${PI} 0
    echo
    round ${PI} 1
    echo
    round ${PI} 2
    echo
    round ${PI} 3
    echo
    round ${PI} 4
    echo
    round ${PI} 5
    echo
    round ${PI} 6
    echo
    
    # Outputs:
    3
    3.1
    3.14
    3.142
    3.1416
    3.14159
    3.141590
    
    # To store in a variable:
    ROUND_PI=$(round ${PI} 3)
    echo ${ROUND_PI}
    
    # Outputs:
    3.142
    

    【讨论】:

    • 尝试“圆形 xzzzzzzzz” ;-)
    【解决方案3】:

    一个小技巧是在您的输入中添加0.0005,这样您的数字就会正确四舍五入。

    【讨论】:

    • 或者像@Tim说的使用printf
    • 如果要四舍五入到三个位置,实际上应该添加.0005,而不是.005。但是你为什么不能这样做呢?
    • 但是您必须先设置一个更大的比例 > 3(否则 0.0005 = 0.000),然后设置比例 = 3 并使用例如 x / 1 计算结果。负 x 也可能会出现意外结果,您可能需要使用 if ( x &lt; 0 ) { x = x - 0.0005; } else { x = x + 0.0005 } 或类似名称。
    【解决方案4】:

    即使 Tim 在 2014 年已经回答了我想分享 Zane 函数的改进版本

    #!/usr/bin/env bash
    
    # round a float number to the given decimal digits
    # if $2 is not given or not a positive integer its set to zero
    
    # float must be in international format, this is more save for scripts
    # to use other format replace LC_ALL=C with your language.
    
    _round_float() {
         local digit="${2}"; [[ "${2}" =~ ^[0-9]+$ ]] || digit="0"
         LC_ALL=C printf "%.${digit}f" "${1}"
    }
    

    函数使用示例:

    # round pi constant
    PI=3.141599236
    
    _round_float $PI 0   3
    _round_float $PI 1   3.1
    _round_float $PI 3   3.142
    _round_float $PI 9   3.141599236
    _round_float $PI -3  3
    _round_float $PI abc 3
    

    您还可以即时调整逗号位置,也就是除/乘以 10

     #!/bin/bash
     # change metric base unit
     UNIT=1234.567890
    
     # comma 1 position right, multiply by 10
     _round_float ${UNIT}e1 3     12345.678
    
     # comma 3 positions left, eg convert milli seconds to seconds
     _round_float ${UNIT}e-3 3     1.234
    
     # comma 3 positions right, eg convert m3 to liters
     _round_float ${UNIT}e3 0     1234567
    

    【讨论】:

      【解决方案5】:

      如果您收到数字 17.928 的舍入错误,请尝试以下操作: 准备好 v=echo "scale = 3; $y" |bc -l 如果 [ $v == 17.928 ] ;然后 回声“17.929” 别的 回声$v 菲

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2016-04-21
        • 2013-12-28
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        相关资源
        最近更新 更多