Quill Quill - 1 year ago 306
Bash Question

Rounding up float point numbers bash

Ok, so I'm trying to round up an input of

, so that it gets an input of
in bash.

My code so far is:

read input
echo "scale = 3; $input" | bc -l

However, when I use this, it doesn't round up, it returns

Does anyone know any solutions to this?

Answer Source

In case input contains a number, there is no need for an external command like bc. You can just use printf:

printf "%.3f\n" "$input"

Edit: In case the input is a formula, you should however use bc as in one of the following commands:

printf "%.3f\n" $(bc -l <<< "$input")
printf "%.3f\n" $(echo "$input" | bc -l)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download