BC – no “\n” at the end + start with zeros?

This is a bc output, e.g.:

Input:

echo "scale=10; BLA-BLA-HERE-NOT-IMPORTANT" | bc

Output:

.3708446283953709207058828124021300754352578903651372655882743141882
77124645102027246581819139527644919407424570060822470537797066353573
96635.8038454068 days

Two Questions:

  • can the output be rounded to something like “0.3708…”?
  • can I remove the “n”-s from the end?

I can’t find any max width option in bc.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

With the GNU implementation of bc, there is an environment variable you can set called BC_LINE_LENGTH that will either disable the backslash + newline feature or will extend it. Newer versions allow you to disable it with a value of 0 like this:

BC_LINE_LENGTH=0 bc <<<"2^4096"

Older versions don’t have the “0 turn off” feature and require you to set the value to a large enough value so that it doesn’t affect you:

BC_LINE_LENGTH=10000 bc <<<"2^4096"

Seems like this would be a good environment variable to set in your shell if you use bc a lot and don’t like the line wrapping. If you’re using bash, just place this in your .bashrc:

export BC_LINE_LENGTH=0

Method 2

You can try something like this code:

echo "scale = 4;  3.5678/3" | bc | tr 'n' ' '

Setting scale for bc is supposed to do the rounding job. You can substitute the division part with your desired command. The output of bc is again piped to tr, which converts the newline (n) to white space. For the above command I get the following output:

1.1892 <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3247415740725e5d51535e5a5d4146">[email protected]</a>:~/codes$

Method 3

$ OUT=$(bc <<< "2 ^ 256")
$ echo "$OUT"
11579208923731619542357098500868790785326998466564056403945758400791
3129639936

$ OUT=${OUT//$'\n'/}
$ echo "$OUT"
115792089237316195423570985008687907853269984665640564039457584007913129639936


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x