Can you operate with decimals in Bash?

5

Is there any way to work with decimals in Bash? Do operations, obviously. I've tried with let , but it always throws me an error with the decimal part.

Thank you very much.

    
asked by lk2_89 05.09.2018 в 08:50
source

1 answer

4

Depending on the tools you have installed in the system you can perform operations with decimals, but bash does not support them internally :

  

Arithmetic Evaluation

     

The shell allows arithmetic expressions to be evaluated, under certain circumstances. Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.

In Spanish:

  

Arithmetic Assessment

     

The shell allows you to evaluate arithmetic expressions under certain circumstances. The evaluation is done in fixed-width integers (32 or 64 bits) without overflow checking, although the division between 0 will be captured and treated as an error.

You can tell if the integer size is 64 bits by trying:

$ echo $((1 << 63))
-9223372036854775808
$ echo $((1 << 64))
1

Using tools installed in the system:

# (En ksh93, zsh y yash, pero no bash)
echo "$((10.5/2))"
awk "BEGIN {print 10.5/2}"         # 5.25
bc <<< "10.5/2"                    # 5
# El resultado se redondea, por lo que si quieres mantener parte decimal:
bc <<< "scale=4; 10.5/2"           # 5.2500
node -pe "10.5/2"                  # 5.25
python -c "print 10.5/2"           # 5.25
php -r 'echo 10.5/2, PHP_EOL;'     # 5.25

To store results you can use:

#!/bin/bash

echo -n "Introduzca A: "
read A
echo -n "Introduzca B: "
read B
RESULTADO=$(bc <<< "scale=4; $A * $B")
echo "$A x $B = $RESULTADO"

A test run could be:

$ bash prueba.sh
Introduzca A: 4.5
Introduzca B: 2.3
4.5 x 2.3 = 10.35
    
answered by 05.09.2018 / 09:32
source