Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add floating number in shell?

a=-1.4
b=42273.85
awk "BEGIN {print ($a + $b)}"

42272.4

I am expecting result as 42272.45, what is wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You didn’t specify a precision so awk picked one for you (%.6g, the default for CONVFMT, see https://www.gnu.org/software/gawk/manual/gawk.html#Built_002din-Variables):

a=-1.4
b=42273.85
awk -v a="$a" -v b="$b" 'BEGIN {printf "%.2f\n", (a + b)}'
42272.45

I’m also correcting your use of shell variables in an awk script above, see How do I use shell variables in an awk script?.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading