theGrayFox
theGrayFox

Reputation: 931

Bash - Formatting values

I've written a simple account script in bash and I couldn't find out the standard way of how displaying a floating point value. Is this the best solution using awk? Balance is also printing out 0.00, did I forget to include something?

#!/bin/bash

function printBalance()
{
    echo | awk 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }'
    sleep 1
}

function makeWithdraw()
{
    echo -en "\nWithdraw an amount: "
    read deposit

    if [ "$withdraw" -gt "$balance" ]; then
      echo -en "\nInsufficient funds"
      sleep 1
    else
      balance=$(( balance - withdraw ))
    fi
}

balance=$((RANDOM%100+1))

# code continues...

Upvotes: 1

Views: 88

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263287

Just use bash's built-in printf command:

$ printf '%.2f\n' 123.456
123.46

I'd also suggest using printf rather than echo for anything complicated. There are multiple versions of echo in various shells and as separate programs. The same is true of printf, but its behavior is much more consistent.

For example, rather than

echo -en "\nWithdraw an amount: "

you can use:

printf '\nWithdraw an amount: '

or, if there's a possibility the string could contain % characters:

printf '\n%s: ' 'Withdraw an amount'

Upvotes: 3

fedorqui
fedorqui

Reputation: 289755

Now I see what was missing: awk needs to have the variable balance given:

If you have $myvar you have to:

awk -v awk_internal_var=${myvar} '{printf "%s", awk_internal_var}'

In your case:

echo | awk -v balance=${balance} 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }'

So that's why it was printing 0.00: because it did not get the value.

Upvotes: 3

Zombo
Zombo

Reputation: 1

Greg says awk should do it

$ awk 'BEGIN {printf "%.3f\n", 10 / 3}'
3.333

Upvotes: 0

Related Questions