Saturday, May 4, 2024
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 6388  / 2 Years ago, thu, october 27, 2022, 7:39:23

I need to add some real numbers in a script. I tried:



let var=2.5+2.5 


which gives me an error - invalid arithmetic operator and then I tried:



let var=2,5+2,5 


which does not give me an error, but it gives me a wrong result -2 in this case.



Why? How to add real numbers using let or other command?


More From » command-line

 Answers
5

The first variant (let var=2.5+2.5) doesn't work because bash doesn't support floating point.



The second variant (let var=2,5+2,5) works, but it may not be what you wish because comma has another meaning in this case: it's a separator, command separator. So, your command is equivalent in this case with the following three commands:



let var=2
let 5+2
let 5


which are all valid and because of this you get var=2.



But, the good news is that you can use bc to accomplish what you wish. For example:



var=$(bc <<< "2.5+2.5")


Or awk:



var=$(awk "BEGIN {print 2.5+2.5; exit}")


Or perl:



var=$(perl -e "print 2.5+2.5")


Or python:



var=$(python -c "print 2.5+2.5")

[#26294] Friday, October 28, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aclavadoug

Total Points: 317
Total Questions: 103
Total Answers: 125

Location: Bangladesh
Member since Wed, Mar 24, 2021
3 Years ago
;