Search code examples
bashfloating-pointprintf

Reduce the amount of decimals positions using bash printf without rounding


I am using printf to restrict the amount of decimal places of a number to 3 decimal places

printf "%.3f\n" 8.577772
8.578

I want to truncate this number to 3 decimal places WITHOUT rounding up so that it prints as 8.577.

Solutions with printf are preferred.


Solution

  • Assuming this is a variable, which can have any number of places before the decimal:

    $ var=8.577772
    $ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
    8.577
    
    $ var=134.56789
    $ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
    134.567