Even already answered by Tim in 2014 I want to share an improved version of Zane's function
#!/usr/bin/env bash
# round a float number to the given decimal digits
# if $2 is not given or not a positive integer its set to zero
# float must be in international format, this is more save for scripts
# to use other format replace LC_ALL=C with your language.
_round_float() {
local digit="${2}"; [[ "${2}" =~ ^[0-9]+$ ]] || digit="0"
LC_ALL=C printf "%.${digit}f" "${1}"
}
some examples how to use the function:
# round pi constant
PI=3.141599236
_round_float $PI 0 3
_round_float $PI 1 3.1
_round_float $PI 3 3.142
_round_float $PI 9 3.141599236
_round_float $PI -3 3
_round_float $PI abc 3
you can also adjust the comma position aka divide/multiply by 10 on the fly
#!/bin/bash
# change metric base unit
UNIT=1234.567890
# comma 1 position right, multiply by 10
_round_float ${UNIT}e1 3 12345.678
# comma 3 positions left, eg convert milli seconds to seconds
_round_float ${UNIT}e-3 3 1.234
# comma 3 positions right, eg convert m3 to liters
_round_float ${UNIT}e3 0 1234567
printf -v output "%.3f\n" "$input"
to assign printf's output to variable $output.