Sample Header Ad - 728x90

How to format floating point number with exactly 2 significant digits in bash?

24 votes
3 answers
51200 views
I want to print the floating point number with exactly two significant digits in bash (maybe using a common tool like awk, bc, dc, perl etc.). Examples: - 76543 should be printed as 76000 - 0.0076543 should be printed as 0.0076 In both cases the significant digits are 7 and 6. I have read some answers for similar problems like: https://unix.stackexchange.com/questions/167058/how-to-round-floating-point-numbers-in-shell https://unix.stackexchange.com/questions/175744/bash-limiting-precision-of-floating-point-variables but the answers focus on limiting the number of decimal places (eg. bc command with scale=2 or printf command with %.2f) instead of significant digits. Is there an easy way to format the number with exactly 2 significant digits or do I have to write my own function?
Asked by tafit3 (343 rep)
Feb 22, 2016, 11:10 PM
Last activity: May 17, 2022, 05:35 PM