3

How do I get bc to start decimal fractions with a leading zero?

$ bc <<< 'scale=4; 1/3'
  .3333

I want 0.3333.

1
4

bc natively do not support adding zero.

Workaround is:

echo 'scale=4; 1/3' | bc -l | awk '{printf "%.4f\n", $0}'

0.3333

"\n" - add a new line.

"%f" - floating point

"%.4f" - the number of digits to show after the decimal point. here it is 4.

2

Unfortunately bc is written in such a way that you cannot. This statement also applies to its neighbor dc. People, as a solution, usually suggest using some text-processing tool to change bc output, or use completely different tool like perl or python which has different syntax, but to me they seems to be too heavy for such simple task.

From your other questions it looks that you are zsh user so I would suggest zcalc, which has very similar syntax for basic operations like bc:

$ zcalc -e '1/3'
0.333333

First you need to load this function (e.g. inside .zshrc) and probably you may want to always treat all numbers as a floating point with -f option:

autoload -U zcalc
alias zcalc='zcalc -f'

As a bonus, you can define special prompt for the calculator with ZCALCPROMPT parameter, for details look at man zshcontrib.

1
  • One day, when I get mad at this enough, I'll fix Linux pipelines to be executable fully in-process, sans execs, forks, and context switches, ending this stupid builtin/external dichotomy once and for all. – PSkocik Jun 25 '16 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.