bash 如何在bash中将浮点数四舍五入到小数点后3位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31124865/
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
How to round a floating point number upto 3 digits after decimal point in bash
提问by Enamul Hassan
I am a new bash
learner. I want to print the result of an expression given as input having 3 digits
after decimal point with rounding if needed.
I can use the following code, but it does not round. Say if I give 5+50*3/20 + (19*2)/7
as input for the following code, the given output is 17.928
. Actual result is 17.92857...
. So, it is truncatinginstead of rounding. I want to round it, that means the output should be17.929
. My code:
我是一个新的bash
学习者。如果需要,我想打印作为输入给出的表达式的结果,3 digits
小数点后带有四舍五入。我可以使用以下代码,但它不会四舍五入。假设如果我5+50*3/20 + (19*2)/7
将以下代码作为输入,则给定的输出是17.928
. 实际结果是17.92857...
。所以,它是truncating而不是四舍五入。我想把它四舍五入,这意味着输出应该是17.929
. 我的代码:
read a
echo "scale = 3; $a" | bc -l
Equivalent C++
code can be(in main
function):
等效C++
代码可以是(在main
函数中):
float a = 5+50*3.0/20.0 + (19*2.0)/7.0;
cout<<setprecision(3)<<fixed<<a<<endl;
回答by nils
What about
关于什么
a=`echo "5+50*3/20 + (19*2)/7" | bc -l`
a_rounded=`printf "%.3f" $a`
echo "a = $a"
echo "a_rounded = $a_rounded"
which outputs
哪个输出
a = 17.92857142857142857142
a_rounded = 17.929
?
?
回答by anubhava
You can use awk:
您可以使用 awk:
awk 'BEGIN{printf "%.3f\n", (5+50*3/20 + (19*2)/7)}'
17.929
%.3f
output format will round up the number to 3 decimal points.
%.3f
输出格式会将数字四舍五入到 3 个小数点。