舍入浮点数bash

Qui*_*ill 17 floating-point bash shell decimal rounding

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

到目前为止我的代码是:

read input
echo "scale = 3; $input" | bc -l
Run Code Online (Sandbox Code Playgroud)

但是,当我使用它时,它不会向上舍入,而是返回17.928.

有谁知道任何解决方案吗?

Tim*_*ann 25

如果input包含数字,则不需要外部命令bc.你可以使用printf:

printf "%.3f\n" "$input"
Run Code Online (Sandbox Code Playgroud)

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

printf "%.3f\n" $(bc -l <<< "$input")
printf "%.3f\n" $(echo "$input" | bc -l)
Run Code Online (Sandbox Code Playgroud)


Zan*_*per 5

要扩展 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
Run Code Online (Sandbox Code Playgroud)