Sometimes, we may need to round off a floating point integer in bash scripts.
Suppose in a bash script we may need to compare two numbers stored in two variable. One is a integer and other is a floating point number. Then, it is important that, we have to round off the floating point number before comparison, otherwise we are always going to get error message.
A useful command to round off floating point number is "bc"
Lets, see how bc command can help us. Everyone of us know that, 100/3 is 3.03030303030303..
So, let us assume that, in a scenario we may want only the number "3" to be stored in a variable.
Then the below method is useful:
-----
[root@MANINMANOJ]#new=`echo '100/33' | bc`
[root@MANINMANOJ]#
[root@MANINMANOJ]#echo $new
3
Suppose in a bash script we may need to compare two numbers stored in two variable. One is a integer and other is a floating point number. Then, it is important that, we have to round off the floating point number before comparison, otherwise we are always going to get error message.
A useful command to round off floating point number is "bc"
Lets, see how bc command can help us. Everyone of us know that, 100/3 is 3.03030303030303..
So, let us assume that, in a scenario we may want only the number "3" to be stored in a variable.
Then the below method is useful:
-----
[root@MANINMANOJ]#new=`echo '100/33' | bc`
[root@MANINMANOJ]#
[root@MANINMANOJ]#echo $new
3
-------
Now, in another scenario we may want to have 5 digits after decimal point. Then, we have to use "scale" as below:
----
[root@MANINMANOJ]#new=`echo 'scale=5;100/33' | bc`
[root@MANINMANOJ]#
[root@MANINMANOJ]#echo $new
3.03030
[root@MANINMANOJ]#
-----
In above example five numbers after decimal point is considered in the output.
Kool :)
No comments:
Post a Comment
Note: only a member of this blog may post a comment.