Bash 脚本:指定 bc 输出数字格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2965411/
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-09 19:19:57  来源:igfitidea点击:

Bash script: specify bc output number format

bashformat

提问by Andrey Kazak

Greetings!

你好!

I uses to make some calculations in my script. For example:

我使用在我的脚本中进行一些计算。例如:

bc
scale=6
1/2
.500000

For further usage in my script I need "0.500000" insted of ".500000".

为了在我的脚本中进一步使用,我需要“0.500000”插入“.500000”。

Could you help me please to configure bc output number format for my case?

你能帮我为我的情况配置 bc 输出数字格式吗?

回答by nad2000

In one line:

在一行中:

printf "%0.6f\n" $(bc -q <<< scale=6\;1/2)

回答by janmoesen

Quick and dirty, since scaleonly applies to the decimal digits and bcdoes not seem to have a sprintf-like function:

快速而肮脏,因为scale仅适用于十进制数字并且bc似乎没有类似sprintf功能:

$ bc
scale = 6
result = 1 / 2
if (0 <= result && result < 1) {
    print "0"
}
print result;

回答by Paused until further notice.

Just do all your calculations and output in awk:

只需在 awk 中完成所有计算和输出:

float_scale=6
result=$(awk -v scale=$floatscale 'BEGIN { printf "%.*f\n", scale, 1/2 }')

As an alternative, if you'd prefer to use bcand not use AWK alone or with 'bc', Bash's printfsupports floating point numbers even though the rest of Bash doesn't.

作为替代方案,如果您更喜欢bc单独使用而不是使用 AWK 或与 'bc' 一起使用,则 Bashprintf支持浮点数,即使 Bash 的其余部分不支持。

result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
result=$(printf '%*.*f' 0 "$float_scale" "$result")

The second line above could instead be:

上面的第二行可以改为:

printf -v $result '%*.*f' 0 "$float_scale" "$result"

Which works kind of like sprintfwould and doesn't create a subshell.

这有点像sprintf并且不会创建子shell。

回答by SteinAir

echo "scale=3;12/7" | bc -q | sed 's/^\./0./;s/0*$//;s/\.$//'

回答by Andrey Kazak

I believe here is modified version of the function:

我相信这是该功能的修改版本:

float_scale=6

function float_eval()
{
    local stat=0
    local result=0.0
    if [[ $# -gt 0 ]]; then
        result=$(echo "scale=$float_scale; $*" | bc -q | awk '{printf "%f\n", 
scale=6
output=1/2
print output
}' 2>/dev/null) stat=$? if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi fi echo $result return $stat }

回答by irkenInvader

Can you put the bc usage into a little better context? What are you using the results of bc for?

你能把 bc 的用法放在更好的上下文中吗?你用 bc 的结果做什么?

Given the following in a file called some_math.bc

在名为的文件中给出以下内容 some_math.bc

$ bc -q some_math.bc | awk '{printf "%08f\n", ##代码##}'
0.500000

on the command line I can do the following to add a zero:

在命令行上,我可以执行以下操作来添加零:

##代码##

If I only needed the output string to have a zero for formatting purposes, I'd use awk.

如果我只需要输出字符串有一个零用于格式化目的,我会使用 awk。