使用 bash 进行浮点运算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20718482/
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
floating-point operations with bash
提问by quickbug
how can I transform the string "620/100" into "6.2" in a bash script
如何在 bash 脚本中将字符串“620/100”转换为“6.2”
The context of my question is about image processing. EXIF data are coding the focal length in fractional format, while I need the corresponding decimal string.
我的问题的上下文是关于图像处理的。EXIF 数据以分数格式编码焦距,而我需要相应的十进制字符串。
Thanks for helping, Olivier
谢谢你的帮助,奥利维尔
回答by anubhava
Use bc -l
用 bc -l
bc -l <<< "scale=2; 620/100"
6.20
OR awk:
或 awk:
awk 'BEGIN{printf "%.2f\n", (620/100)}'
6.20
回答by devnull
bash
doesn't support floating point.
bash
不支持浮点。
You could use bc
:
你可以使用bc
:
$ echo "50/10" | bc -l
5.00000000000000000000
$ echo "scale=1; 50/10" | bc -l
5.0
回答by quickbug
Thank-you for the answers. bc was what I needed.
谢谢你的回答。bc 是我需要的。
I dont know if posting the result is of any use. Anyway, this the final piece of code for exteracting the focal length of a photo and print it in decimal format. It is supposed to work for all cameras. Tested on 4 cameras of 3 different brands.
我不知道发布结果是否有任何用处。无论如何,这是提取照片焦距并以十进制格式打印的最后一段代码。它应该适用于所有相机。在 3 个不同品牌的 4 个相机上进行了测试。
F="your_image.JPG"
EXIF=$(exiv2 -p v "$F")
FocalFractional=$( echo "$EXIF" | grep -E '[^ ]* *Photo *FocalLength '| grep -iohE "[^ ]* *$" )
Formula="scale=2; "$FocalFractional
FocalDecimal=$( bc -l <<< "$Formula" )
echo $ FocalDecimal