0

I used the below line of script in my shell code Percent=echo "scale=2; $DP*100/$SDC" | bc it returns .16 as output but i need it as 0.16

Keerthisairam
  • 81
  • 3
  • 10

1 Answers1

0

Posix-compliant solution using bc:

#!/bin/sh
Percent="$(echo "
  scale=2;
  a = $DP * 100 / $SDC;
  if (a > -1 && a < 0) { print "'"-0"'"; a*=-1; }
  else if (a < 1 && a > 0) print 0;
  a" | bc)"

That's kind of ugly with all of those special checks for cases when the answer is between -1 and 1 (exclusive) but not zero.

Let's use this Posix-compliant solution using awk instead:

#!/bin/sh
Percent="$(echo "$DP" "$SDC" |awk '{printf "%.2f", $1 * 100 / $2}')"

Z shell can do this natively:

#!/bin/zsh
Percent="$(printf %.2f $(( DP * 100. / SDC )) )"

(The dot is necessary to instruct zsh to use floating point math.)

Native Posix solution using string manipulation (assumes integer inputs):

#!/bin/sh
#                                    # e.g. round down   e.g. round up
#                                    # DP=1 SDC=3        DP=2 SDC=3
Percent=$(( DP * 100000 / SDC + 5))  # Percent=33338     Percent=66671
Whole=${Percent%???}                 # Whole=33          Whole=66
Percent=${Percent#$Whole}            # Percent=338       Percent=671
Percent=$Whole.${Percent%?}          # Percent=33.33     Percent=66.67

This calculates 1,000 times the desired answer so that we have all the data we need for the final resolution to the hundredths. It adds five so we can properly truncate the thousandths digit. We then define temporary variable $Whole to be just the truncated integer value, we temporarily strip that from $Percent, then we append a dot and the decimals, excluding the thousandths (which we made wrong so we could get the hundredths rounded properly).

Adam Katz
  • 14,455
  • 5
  • 68
  • 83