Search code examples
bashmathprintfroundingbc

Is it possible to use BASH/bc/printf to round a float to its first significant figure?


I've found tons and tons of information about rounding a float to a specific number of decimal places by using 'scale' with BC and '%.xf' with printf, but if I'm working with numbers that don't always have the same format like I've shown below, is there a way to round it to the first decimal place that isn't a zero?

For example, say I have a list of numbers like this:

0.0008234535225
0.00547889294
0.000003243322

Is there a way for me to convert them to something like this?:

0.0008
0.005
0.000003

Every Google result I've come across is talking about rounding to a specific number of digits instead of to the first significant number and I'm not having much success in filtering them from the search results, so it's making figuring out this problem entirely on my own a bit difficult.

Could someone please point me in the right direction?


Solution

  • The following will truncate your numbers to the first non 0 digit:

    grep -o "0.0*." <<< "$NUMBER"
    

    For example:

    grep -o "0.0*." <<< "0.000003243322"
    

    Prints:

    0.000003