bc
handles numbers as integers:
# echo "100/3" | bc
33
bc -l
handles numbers as floating point objects:
# echo "100/3" | bc -l
33.33333333333333333333
Is there a way to limit the number of digits after the decimal point?
bc
handles numbers as integers:
# echo "100/3" | bc
33
bc -l
handles numbers as floating point objects:
# echo "100/3" | bc -l
33.33333333333333333333
Is there a way to limit the number of digits after the decimal point?
Set the
scale
special variable:scale
works only for division; if some geeks need it in multiplication, then you can do achieve this by using string manipulation. Say if you need to multiply32 * 0.60
, answer is19.20
. If you need to get it 19 alone in answer you can get it by different methods.Using String Manipulation
String Manipulation syntax:
${Variable%pattern}
, this will delete short matching pattern that comes after%
. For more String manipulation details see the Advanced Bash-Scripting Guide.Using
Scale
as stated by**chronitis**
To get rid of the trailing 0s, instead of string manipulation, one can also do a divide by 1.
In addition to previous answers
Returns
Add Math operations to get only 2 decimal numbers - (NUMBER*100)/100
Now returns
you can also use printf command to round off result upto 3 decimals
Round-off
scale=2 truncates the answer to two decimal digits, but we can achieve round-off like so: