Home > database >  How to printf fixed number or digits in floating in bash
How to printf fixed number or digits in floating in bash

Time:02-28

I want to output floating numbers with exact number of digits without padding in the front, since I want to prepend $ sign For example I read numbers:

1.2345
12.345
123.456

and I want output:

$1.23450
$12.3450
$123.456

I tried many different variations in printf but can't fix number of total digits. I also didn't find answer to this particular problem
printf "$%.7f\n" 1.2345 12.345 123.456
neither with "$%.7f\n "$f\n "$%6.4f\n "$%.7g\n
Do I need to get different formatting for for different magnitude of numbers ie 1, 10, 100?

CodePudding user response:

How to printf fixed number or digits in floating in bash

Print first 7 characters from the printed number.

printf "$%.7s\n" "$(printf "%.6f" 1234.2345)"

Do I need to get different formatting for for different magnitude of numbers ie 1, 10, 100?

Yes, you should implement your own formatting function for custom formatting requirements. There is no such printf formatting specifier for what you want.

CodePudding user response:

Here is an alternative to using floating-point formatting in Bash:

#!/usr/bin/env bash

float_numbers=(1.2345 12.345 123.456)

# Get the longest number's length
for float in "${float_numbers[@]}"; do
  max_length=$((${#float} > max_length ? ${#float} : max_length))
done

for float in "${float_numbers[@]}"; do
  # Generate needed padding
  printf -v padding '%-*s' $((max_length - ${#float})) ''

  # Print $float followed by its 0 padding
  printf '$%s%s\n' "$float" "${padding// /0}"
done
  • Related