kaibob
August 17th, 2009, 03:15 PM
I am attempting to format numbers in a bash shell script as follows:
* Numbers are rounded to 2 decimal places.
* Trailing zeros are removed.
* Thousand separators are used (commas in my locale).
To give some examples:
1) 6 is formatted as 6
2) 6.60 is formatted as 6.6
3) 6.666 is formatted as 6.67
4) 6666 is formatted as 6,666
I tried two alternatives as shown below. The first works but only if the number contains 5 digits or less. The second works but is cumbersome.
printf "%'g\n" "${number}"
printf "%'.2f\n" "${number}" | sed 's/\.00$// ; s/\(\.[1-9]\)0$/\1/'
Is there an easier way to do this?
As an aside, I'm just learning shell scripting, so another language is not an option right now.
Thanks for the help.
* Numbers are rounded to 2 decimal places.
* Trailing zeros are removed.
* Thousand separators are used (commas in my locale).
To give some examples:
1) 6 is formatted as 6
2) 6.60 is formatted as 6.6
3) 6.666 is formatted as 6.67
4) 6666 is formatted as 6,666
I tried two alternatives as shown below. The first works but only if the number contains 5 digits or less. The second works but is cumbersome.
printf "%'g\n" "${number}"
printf "%'.2f\n" "${number}" | sed 's/\.00$// ; s/\(\.[1-9]\)0$/\1/'
Is there an easier way to do this?
As an aside, I'm just learning shell scripting, so another language is not an option right now.
Thanks for the help.