bashmathbcexpr

Bash Math Oddity (Floating Point Division)


So I'm having some trouble with bash / bc math here..

I'm trying to print the filesize in of a backup after I move it to my gdrive via rclone for backup. So I get the filesize via an rclone ls statement with awk print $1 which works great.

In my specific example, I get the value of 1993211 (bytes).

So in my printing code I try to divide this by 1048576 to get it into mb. Which should give me 1.9 mb.

However, $ expr 1993211 / 1048576 | bc -l

prints 1

I've tried various other math options listed here (incl via python / node) and I always get 1 or 1.0. How is this possible?

The calculation should be 1993211 / 1048576 = 1.90087413788

Any idea whats going on here?


Solution

  • That's because it does integer division. Do get floating point division you could run:

    bc -l <<< '1993211 / 1048576'
    

    which returns: 1.90087413787841796875

    or you can set the number of decimals using scale:

    bc -l <<< 'scale=5; 1993211 / 1048576'
    

    which returns: 1.90087