Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed rounding a number to 2 decimals

I have a number i.e. 123.456789 and my question is how to round this to two decimals after dot, so it look like 123.46 using sed? Any ideas? Alternatively, how to cut the rest after 2 decimals so in the end it would look like this: 123.45? Thanks in advance!

like image 226
user1246172 Avatar asked Nov 17 '25 20:11

user1246172


2 Answers

Actually sed is not the rght tool for this, your should better use awk. Create an awk script like this:

echo 123.45567 | awk '{printf("%.2f\n", $1)}'

OR using BASH printf:

printf "%.2f\n" 123.45567

OUTPUT:

123.46

like image 193
anubhava Avatar answered Nov 19 '25 09:11

anubhava


Truncating it can be done with something like:

pax> echo hello 123.4567 goodbye | sed 's/\(\.[0-9][0-9]\)[0-9]*/\1/g'

hello 123.45 goodbye

This basically works by finding a string of the form .dd[ddd...] (where d is a digit) and replacing the whole thing with just the .dd (the parentheses act to to capture the .dd bit).

Rounding it is a little more difficult since it's not simple text substitution (you have to change the final digit to add one, if the next digit is five or more). You may need to resort to slightly more adaptable tools for that.

One way to do this (though I'm pretty certain it's not the best way) is with Perl:

pax> echo hello 123.4567 9876.54321 goodbye | perl -ne '
    @x = split;
    for ($i = 0; $i <= $#x; $i++) {
        if ($x[$i] =~ /^[0-9]*\.[0-9]+$/) {
            $x[$i] = int ($x[$i] * 100 + .5) / 100;
        };
        print "$x[$i] ";
    };
    print "\n";'

hello 123.46 9876.54 goodbye

This does the rounding operation on every field that matches the desired pattern but, as stated, it's pretty ugly - I'm sure there are better ways (brian d foy, where are you?)

like image 41
paxdiablo Avatar answered Nov 19 '25 10:11

paxdiablo