Reputation: 1105
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!
Upvotes: 2
Views: 16019
Reputation: 65791
Since no one's managed to do rounding with sed
yet anyway, here's a Python example for you:
$ echo "echo hello 123.4567 goodbye" | python -c "import sys, re
for l in sys.stdin:
print re.sub(r'\d*\.\d{3,}', lambda x: str(round(float(x.group()), 2)), l)"
echo hello 123.46 goodbye
You can change 2 to something else to change the rounding accuracy.
Upvotes: 1
Reputation: 785108
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
123.46
Upvotes: 14
Reputation: 881383
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?)
Upvotes: 6