Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

floating-point operations with bash

how can I transform the string "620/100" into "6.2" in a bash script

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.

Thanks for helping, Olivier

like image 845
quickbug Avatar asked Dec 21 '13 11:12

quickbug


People also ask

How do I use floating point numbers in bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part. Rounding as needed.

Does bash support floating point?

2. Bash arithmetic expansion does not support floating-point arithmetic. When attempting to divide in this case, the output shows zero (0). The result of integer division must be an integer.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is $1 and $2 in bash?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)


1 Answers

Use bc -l

bc -l <<< "scale=2; 620/100"
6.20

OR awk:

awk 'BEGIN{printf "%.2f\n", (620/100)}'
6.20
like image 95
anubhava Avatar answered Nov 15 '22 20:11

anubhava