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

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

How to round a floating point number upto 3 digits after decimal point in bash

bashfloating-pointfloating-point-precisionfloating-point-conversion

提问by Enamul Hassan

I am a new bashlearner. I want to print the result of an expression given as input having 3 digitsafter 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)/7as 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 mainfunction):

等效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

%.3foutput format will round up the number to 3 decimal points.

%.3f输出格式会将数字四舍五入到 3 个小数点。