Use numfmt instead of custom byte-counting

This commit is contained in:
Dan Church 2023-04-21 10:48:12 -05:00
parent 8dcfacd5d7
commit 7da19cfaf3
Signed by: h3xx
GPG Key ID: EA2BF379CD2CDBD0
1 changed files with 4 additions and 37 deletions

41
optipdf
View File

@ -116,43 +116,10 @@ file_size() {
# produces a human-readable size from the byte count passed to it
hr_size() (
declare -i BYTES=$1
#UNITS=(B KB MB GB TB PB EB ZB YB) # shell math can only go so far...
UNITS=(B KB MB GB TB)
FACT=1024
THRESH=9/10
DECIMALS=1
DECIMALS_FACTOR=$(( 10 ** DECIMALS ))
# cycle through units from largest to smallest, exiting when it finds the
# largest applicable unit
for (( EXP = ${#UNITS[@]} - 1; EXP > -1; --EXP )); do
# check if the unit is close enough to the unit's size, within the
# threshold
if [[ $BYTES -gt $((FACT ** EXP * $THRESH)) ]]; then
# we found the applicable unit
# must multiply by a factor of 10 here to not truncate
# the given number of decimal places after the point
HR_VAL=$(( BYTES * DECIMALS_FACTOR / FACT ** EXP ))
# put the decimal point in
if [[ $DECIMALS -gt 0 ]]; then
HR_VAL=$(( HR_VAL / DECIMALS_FACTOR )).$(( HR_VAL % DECIMALS_FACTOR ))
fi
HR_UNIT=${UNITS[$EXP]}
break
fi
done
if [[ -z $HR_UNIT ]]; then
HR_VAL=$BYTES
HR_UNIT=${UNITS[0]}
fi
printf '%g %s\n' "$HR_VAL" "$HR_UNIT"
numfmt \
--to=iec \
--suffix=B \
"$@"
)
setup_tempdir() {