0

At the input I have to enter two numbers and output their sum, difference, composition and division (to two decimal places). When dividing, for example, 1 by 3, I get .33 (and -1 by 3 gives me -.00). But I need to get 0.33, what is wrong? Bash code:

#!/bin/bash
x=$1
y=$2
if((x==0))||((y==0))
then 
    printf '%s' "$(( x+y )) "
    printf '%s' "$(( x-y )) "
    printf "$(( x*y )) "
    printf "#"
else
    d=$(echo "$x/$y" | bc -l)
    printf '%s' "$(( x+y )) "
    printf '%s' "$(( x-y )) "
    printf '%s'"$(( x*y )) "
    printf '%s' "$d" | cut -b 1-4
fi
Cyrus
  • 77,979
  • 13
  • 71
  • 125
  • 4
    See https://mywiki.wooledge.org/BashFAQ/022 – Shawn Oct 10 '21 at 19:30
  • Some bc implementations omit the leading 0, some don't. Apparently yours do. – oguz ismail Oct 10 '21 at 19:37
  • 3
    fwiw, when I run your code with `x=-1` and `y=3` I get `-.33`, though to insure you're getting a minimum number of digits you may wish to include the `scale=X` to the stream you feed to `bc` (see the link Shawn's provided); as for the **formatting** of output (eg, prefacing the output with leading `0`) keep in mind this is where `printf` is your friend, eg, `printf '%0.2f' "$d"` (no need for the `| cut -b 1-4`)=> `-0.33` – markp-fuso Oct 10 '21 at 19:38
  • See my (numerous) comments on the topic [here](https://stackoverflow.com/questions/69458409/how-to-use-multiplication-and-division-when-invoking-the-arithmetic-expansion-op#comment122769097_69458409). TL;DR: `numerator=1; denominator=3; big=1000000000; blah=$(((big * numerator + denominator / 2) / denominator)); pseudo_float="$((blah / big)).$((blah % big))"; echo "$pseudo_float";` and tweak `big` to your liking. – Andrej Podzimek Oct 11 '21 at 20:24

0 Answers0