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?
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.
Sign up to join this communitySet the scale
special variable:
$ echo "scale=2; 100/3" | bc
33.33
.5
. ~$ echo "scale=2; 12/104" | bc
.11
If rounded up this would be .12
. However, it should still do the job for my task.
echo "result = (100/180) * 180; scale=2; result / 1" | bc -l
. Now you get 99.99
.
Aug 13, 2018 at 1:44
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 multiply 32 * 0.60
, answer is 19.20
. If you need to get it 19 alone in answer you can get it by different methods.
Using String Manipulation
$ S=$(echo "32*.60" | bc ) ; echo ${S%.*}
19
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**
$ echo "scale=0; 32*60/100" | bc
19
To get rid of the trailing 0s, instead of string manipulation, one can also do a divide by 1.
$ echo "0.232 * 1000" | bc
232.000
$ echo "0.232 * 1000 / 1" | bc
232
you can also use printf command to round off result upto 3 decimals
# printf "%.3f\n" $(echo "100/3" | bc -l)
3.333
In addition to previous answers
echo "scale=2; 1.0150876" | bc
Returns
1.0150876
Add Math operations to get only 2 decimal numbers - (NUMBER*100)/100
echo "scale=2; (1.0150876 * 100) / 100" | bc
Now returns
1.01
Round-off
scale=2 truncates the answer to two decimal digits, but we can achieve round-off like so:
$ echo "a=12/104; scale=2; (a+0.005)/1" | bc -l
.12
scale=0;1234*1.1
, you have to write it asscale=0;1234*1.1/1
to get1357
. Otherwise, no matter the value ofscale
, you get1357.4
.1234*1.0
will give you1234.0