Sunday, January 28, 2024

[SOLVED] How to printf fixed number or digits in floating in bash

Issue

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 "$%07f\n "$%6.4f\n "$%.7g\n
Do I need to get different formatting for for different magnitude of numbers ie 1, 10, 100?


Solution

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.



Answered By - KamilCuk
Answer Checked By - David Goodson (WPSolving Volunteer)