2014-10-20 56 views
15

好的,所以我试图将输入17.92857四舍五入,以便在bash中输入17.929向上舍入浮点数bash

到目前为止我的代码是:

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

然而,当我用这个,它不圆了,它返回17.928

有没有人知道任何解决方案?

+0

[看看这个(http://stackoverflow.com/a/2395601/3913686) – 2014-10-20 12:18:23

+0

您可以使用'printf -v output'%.3f \ n“”$ input“'将printf的输出分配给变量$ output。 – Cyrus 2014-10-20 12:46:42

+0

必须来自hackerrank(https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations) – bergie3000 2017-02-03 18:12:49

回答

19

如果input包含一个数字,则不需要外部命令,如bc。你可以只用printf

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

编辑:如果输入的是一个公式,你应该使用,无论bc如下面的命令之一:

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

我扩展了我的答案,看看它是否适合你。 – 2014-10-20 12:34:46

1

一个小窍门是将0.0005添加到您的输入中,这样您就可以正确地取得您的号码。

+0

或者像@Tim所说的使用printf – 2014-10-20 12:21:40

+0

如果你四舍五入到三个地方,你应该添加'.0005',而不是'.005'。但为什么你不能那样做? – 2014-10-20 12:35:44

+0

我编辑了我的答案,谢谢! – 2014-10-20 12:41:34

-2

如果您收到的舍入误差与数17.928试试这个: 读出用Y V = echo "scale = 3; $y" |bc -l 如果[$ V == 17.928]。然后 回声 “17.929” 其他 回声$ V 网络

0

你可以写一个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