0

With dc external tool bash tend to not print at the right of the decimal point.

#!/bin/bash    
a[0]=-0.5    
`echo "scale=10;${a[0]}/1"|bc -l`

With the command represented above bash will print -.5000000000.

How can I add the zero between the minus signal and the point -0.5000000000

PS: I do print a[1]=0 with 10 decimal cases?

  • google 'bash bc print leading 0' and you'll get a list of answers (hint: `bc|dc` can't do this), eg: https://stackoverflow.com/questions/8402181/how-do-i-get-bc1-to-print-the-leading-zero, https://stackoverflow.com/questions/16482353/adding-a-leading-zero-to-a-float-number-in-a-bash-script, https://unix.stackexchange.com/questions/292087/how-do-i-get-bc-to-start-decimal-fractions-with-a-leading-zero – markp-fuso May 06 '20 at 21:22

1 Answers1

0

Instead of bc you may consider this awk that does floating point match and formatting using printf:

a[0]=-0.5

awk -v n="${a[0]}" 'BEGIN{printf "%.10f\n", n/1}'

-0.5000000000
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • No, but a similar command worked https://unix.stackexchange.com/questions/292087/how-do-i-get-bc-to-start-decimal-fractions-with-a-leading-zero Thank you – Miguel Cardoso May 07 '20 at 15:07
  • ok but same command works here in this demo: https://ideone.com/9ldj5q – anubhava May 07 '20 at 15:11