Rounding up float point numbers bash
25,332
Solution 1
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)
Solution 2
To extend Tim's answer, you can write a shell helper function round ${FLOAT} ${PRECISION}
for this:
#!/usr/bin/env bash
round() {
printf "%.${2}f" "${1}"
}
PI=3.14159
round ${PI} 0
echo
round ${PI} 1
echo
round ${PI} 2
echo
round ${PI} 3
echo
round ${PI} 4
echo
round ${PI} 5
echo
round ${PI} 6
echo
# Outputs:
3
3.1
3.14
3.142
3.1416
3.14159
3.141590
# To store in a variable:
ROUND_PI=$(round ${PI} 3)
echo ${ROUND_PI}
# Outputs:
3.142
Author by
Quill
#SOreadytohelp former Language Learning pro tempore moderator and part-time Hat Maniac (2015 WinterBash winner)
Updated on July 05, 2022Comments
-
Quill almost 2 years
Ok, so I'm trying to round up an input of
17.92857
, so that it gets an input of17.929
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
17.928
.Does anyone know any solutions to this?
-
Ludovic Feltz over 9 yearsOr like @Tim said use printf
-
Mark Reed over 9 yearsIf you're rounding to three places, you should actually add
.0005
, not.005
. But why can't you do that? -
Max about 5 yearsBut you have to set a larger scale > 3 first (else 0.0005 = 0.000), and then set scale = 3 and compute the result using, e.g.,
x / 1
. There may also be unexpected results for negative x and you may be required to useif ( x < 0 ) { x = x - 0.0005; } else { x = x + 0.0005 }
or similar. -
Gnadelwartz almost 4 yearstry "round xzzzzzzzz" ;-)