TransWikia.com

How to shorten decimal output in bash?

Unix & Linux Asked by PCRevolt on December 17, 2021

Right now I am working on an assignment that involves advanced piping, and one of the questions involves calculating a percent and shortening it to 3 decimal places. I’ve managed to calculate the percent:

echo "$ERRORS" / "$TOTAL" * 100 | bc -l

which gives the correct output: 2.64905226881102814400

ERRORS and TOTAL are both environment variables containing integers.

But I don’t really know how to modify this command to only output 2.649 instead of the full number. I know there is a way to use something called scale with bc to shorten to a certain number of decimal places but I tried echo scale=3; "$ERRORS" / "$TOTAL" * 100 | bc -l and it didn’t work.

What am I doing wrong?

One Answer

Try:

$ ERRORS=1153 TOTAL=43525
$ echo "scale = 3; $ERRORS * 100 / $TOTAL" | bc
2.649

instead. See how in this case, scale = 3 is being fed to bc to set the scale variable of bc, which is the number of digits that it keeps after the radix upon division, and how we did the multiplication by 100 before the division.

Note that it's truncation, not rounding. 8 * 100 / 9, will become 88.888, not 88.889 for instance.

If your shell supports floating point arithmetics (ksh93, zsh, yash), you can also do:

$ printf '%.3fn' "$((ERRORS * 1e2 / TOTAL))"
2.649

(though note that in zsh and ksh93, it's critical the contents of those variables be controlled as that would constitute a command injection vulnerability if not. We use 1e2 (a floating point 100 while 100 is integer) instead of 100. as in ksh93, 100. wouldn't work in locales that use , as the decimal radix).

Or you could use awk:

$ awk -- 'BEGIN{printf "%.3fn", ARGV[1] * 100 / ARGV[2]}' "$ERRORS" "$TOTAL"
2.649

Both of which would give you 88.889% (or possibly 88,889 depending on the locale) for 8 out of 9.

Answered by Stéphane Chazelas on December 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP