6

I am using bc and scale for evaluating a expression however I want it to round up instead of round down. What is the simplest way to do this?

$ read exp
5+50*3/20 + (19*2)/7
$ echo "scale=3; $exp" | bc -l
17.928

However my desired answer is 17.929

I prefer the answer to be an addendum to my answer than something different ground up. Thanks

Here are some of the things I've tried:

$ echo "scale=4; ($exp+0.0005)" | bc -l
17.9290
$ echo "scale=3; ($exp+0.0005)" | bc -l
17.9285

However I want 17.929 as answer with no zero at the end.

Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
  • @dimo414 I don't want to write a function. I saw that before writing this – Mona Jalal May 24 '16 at 04:31
  • You don't need to write a function if you don't want to. The answer - to pipe into `printf` - is what the function does. – dimo414 May 24 '16 at 04:33
  • @MonaJalal: If you write (or copy) the function and put it into your bash startup file, it will always be there waiting for you. Otherwise, you end up having to type *something* long and complicated everytime you want the correctly rounded answer. Seriously, go with the bash function. Call it `bc` if you like. – rici May 24 '16 at 04:57

1 Answers1

7

solved it by using scaling factor of printf as 3, scaling factor of bc as 4 and adding 0.0005 to the expression:

printf "%.3f\n"  $( echo "scale=4; $exp+0.0005" | bc -l ) 
Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
  • 6
    You don't need to add the `0.0005`, `printf` does the rounding properly. You can actually skip the `scale` step completely, this would work just as well: `printf "%.3f\n" $(bc -l <<< "$exp")` – Benjamin W. May 24 '16 at 04:11
  • @BenjaminW. that worked. Thanks. Why did you use <<< here? https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations also can you write it as an answer? thanks! – Mona Jalal May 24 '16 at 04:33
  • @MonaJalal: `<<<` indicates that what follows is a ["here-string"](http://www.gnu.org/software/bash/manual/bash.html#Here-Strings), which is provided to the utility on its standard input, followed by a newline. So `foo <<<"some input"` and `echo "some input"|foo` do essentially the same thing, but there are several advantages to not using a pipe. Also, it's shorter and more readable, once you get to know it. – rici May 24 '16 at 04:48
  • Ah, too late for an answer - but @rici says it all in his comment. – Benjamin W. May 24 '16 at 04:54
  • 4
    This being said, hackerrank is not exactly a haven of best practices. – Benjamin W. May 24 '16 at 04:55