Bash divide floating numbers

 

Dividing floating point number with bash/shell is bit tricky task.

To divide floating point number  we can use bc command.

Lets try with example, here I will divide 1.1 with 2 that is 1.1/2

By simply using bc you will get output as 0, try following command you should get output as 0.

$ echo "1.1/2" | bc

Output:

0

To get output as floating point number we need to use -l option with bc as shown below:

$ echo "1.1/2" | bc -l

Output:

.55000000000000000000

To truncate length of output we can use scale option with above expression.

Lets try to truncate length to 2 with following example:

$ echo "scale=2;1.1/2" | bc -l

Output:

.55

Lets try to truncate length to 2 with following example:

$ echo "scale=5;1.1/2" | bc -l

Output:

.55000

 

Advertisements

One comment on “Bash divide floating numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s