bash 四舍五入浮点数bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26465496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:36:44  来源:igfitidea点击:

Rounding up float point numbers bash

bashshellfloating-pointdecimalrounding

提问by Quill

Ok, so I'm trying to round up an input of 17.92857, so that it gets an input of 17.929in bash.

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

My code so far is:

到目前为止我的代码是:

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

However, when I use this, it doesn't round up, it returns 17.928.

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

Does anyone know any solutions to this?

有谁知道任何解决方案?

回答by Tim Zimmermann

In case inputcontains a number, there is no need for an external command like bc. You can just use printf:

如果input包含数字,则不需要像bc. 你可以只使用printf

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

Edit:In case the input is a formula, you should however use bcas in one of the following commands:

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

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

回答by Zane Hooper

To extend Tim's answer, you can write a shell helper function round ${FLOAT} ${PRECISION}for this:

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

#!/usr/bin/env bash

round() {
  printf "%.f" ""
}

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

回答by Ludovic Feltz

A little trick is to add 0.0005to your input, this way you will have your number round up correctly.

一个小技巧是添加0.0005到您的输入中,这样您就可以正确地对数字进行四舍五入。

回答by reyb

if you're receiving the round-off error with the number 17.928 try this: read y v=echo "scale = 3; $y" |bc -lif [ $v == 17.928 ] ; then echo "17.929" else echo $v fi

如果您收到数字为 17.928 的舍入错误,请尝试以下操作: read y v= echo "scale = 3; $y" |bc -lif [ $v == 17.928 ] ; 然后回声“17.929”否则回声 $v fi