You can do floating point arithmetic using bc
like this:
SEK=$( echo " 6.32138 * $USD " | bc -l )
Explanation:
Bash does not have built it support for floating point arithmetic. Thus, we usually handle these operation using the bc
program. bc
reads an arithmetic expression as a string from the standard input, and prints the result the standard output. Note that the -l
option is necessary for keeping the decimal part of the expression.
In order to get the result from bc
, and store it in a variable, we use command redirection i.e. the $(
)
. Note that there are no spaces before and after the =
in the previous expression.
Complete Example
#!/bin/bash
printf "%s\n" "USD-SEK Currency Convertor"
# Get the value to convert
read -p "Enter a USD: " USD
SEK=$(echo " 6.32138 * $USD " | bc -l )
printf "You will get SEK %s\n" "$SEK" ;# NOTE THAT I CHANGED THIS TO %s FROM %f DUE TO THE LOCALE SETTINGS
Output
$ ./converter.sh
USD-SEK Currency Convertor
Enter a USD: 10
You will get SEK 63.213800
Note that i removed the declare -i SEK
from the script, since the SEK
variable is NOT Integer
The harm of declare -i
. This code produces:
#!/bin/bash
declare -i SEK ;# WOOOPS I FORGOT THE declare -i
printf "%s\n" "USD-SEK Currency Convertor"
# Get the value to convert
read -p "Enter a USD: " USD
SEK=$(echo " 6.32138 * $USD " | bc -l )
printf "You will get SEK %s\n" "$SEK"
This output:
$ ./converter.sh
USD-SEK Currency Convertor
Enter a USD: 10
./converter.sh: line 6: 63.21380: syntax error: invalid arithmetic operator (error token is ".21380")
You will get SEK 0.000000