foges
foges

Reputation: 1536

Constant number of characters in floating point number in bash

I need to do some "pretty" formatting of numbers with bash. I have a string of comma separated floating point numbers in scientific format (ie. either 3.14159 or 1.0601e-12) and I need to create a comma separated list where all numbers have as many characters. It isn't very important whether spaces or zeros are used for filling (ie. ' 3.14' and '3.140000' both work). I tried using printf with "%.12f", but that of course won't work. I'm out of ideas (except for working on a character level, but that seems overly complicated)

I really appreciate the help.

Upvotes: 1

Views: 353

Answers (3)

ormaaj
ormaaj

Reputation: 6617

Zero padding on the left is easier than doing a dynamic decimal precision. Here's a crack at it, not sure if it meets your reqirements.

IFS=, read -ra a <<<'1.234567e+3,5432.623,54326e+4,12.26546e+3,1000000000000,2.3641867e+4'

for idx in "${!a[@]}"; do
    printf -v "b[${b:=0}>b&&(b=$b),idx+1]" '%f%n' "${a[idx]}" b
done

for idx in "${!a[@]}"; do
    printf -v 'a[idx]' '%#.*f' $((b - ${#b[idx+1]})) "${b[idx+1]}"
done

# IFS=, declare -a 'b=("${a[*]}")'
# echo "$b"
printf '%s\n' "${a[@]}"

which gives

1234.567000000
5432.623000000
543260000.0000
12265.46000000
1000000000000.
23641.86700000

Though I'd love to see a more elegant way.

Upvotes: 0

Hai Vu
Hai Vu

Reputation: 40763

For floating point, use %f, for scientific notation, use %e:

$ printf "%12.2f\n" 359.197
      359.20
$ printf "%12.2e\n" 359.197
    3.59e+02

Upvotes: 1

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84413

If you just want to specify a constant number of characters in your output, you can use the field-width modifier. For example, to ensure each field has exactly 24 characters:

printf "%'24f\n" 3.140000 3000

Upvotes: 2

Related Questions