John Tate
John Tate

Reputation: 772

Subtracting floating points using awk

I have a bash script which subtracts 0.0001 from larger numbers with awk. It is not working when numbers have more than four decimal places.

It uses these arguments to awk...

balance=$(awk -vn1="$balance" -vn2="0.0001" 'BEGIN{print (n1-n2) }')

If $balance equals 1.44189949 the number ends up 1.4418 and it needs to be 1.44179949 so I've done something wrong.

I have never dealt with floating point numbers in bash before.

Upvotes: 1

Views: 2805

Answers (4)

Ed Morton
Ed Morton

Reputation: 203512

Just set OFMT you want and print the result, no need for printf:

$ awk -v n1="1.44189949" -v n2="0.0001" -v OFMT="%.8f" 'BEGIN{print n1-n2}'
1.44179949

Upvotes: 2

slevy1
slevy1

Reputation: 3832

If you wish, you may dispense with awk as I did in the following bash script:

balance=1.44189949
printf "%.8f\n" $(bc -l <<< "$balance - 0.0001")

This code utilizes bc which is most adept at handling floating point values. Then printf takes care of rounding it so the result is:

1.44179949

Note that the input for bc is a here string that gets redirected to the command.

Upvotes: 1

John Tate
John Tate

Reputation: 772

It is better to use bc rather than awk to do this calculation.

balance=$(echo $balance-0.0001 | /usr/bin/bc)

The best solution to a problem is usually the easiest one.

Upvotes: 1

repzero
repzero

Reputation: 8412

using printf and change the default rounding behaviour of awk by using "%.8f\n" for eight rounding figures.

awk  -vn1="1.44189949" -vn2="0.0001" 'BEGIN{printf ("%.8f\n",n1-n2)}'

Upvotes: 4

Related Questions