How to convert Kilobytes to Megabytes or gigabytes through terminal?
numfmt
(part of GNU Coreutils) can be used here:
$ sudo fdisk -s /dev/sda | numfmt --to=iec-i --suffix=B --format="%.2f"
931.52MiB
The shell does fixed-width integer arithmetic with no check for overflow. So, when doing a calculation that might involve either large numbers or fractions, bc
is a good choice. To get megabytes:
$ echo "scale=2; $(sudo fdisk -s /dev/sda6) / 1024" | bc
13641.75
To get gigabytes:
$ echo "scale=2; $(sudo fdisk -s /dev/sda6) / 1024^2" | bc
12.70
The assignment scale=2
tells bc
to display two decimal places.