English 中文(简体)
将数字四舍五入到小数点后两位
原标题: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!

问题回答

事实上, sed 不是用于此目的的 rght 工具, 您最好使用 awk 。 创建这样的 Awk 脚本 :

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

使用BASH印刷品f:

printf "%.2f
" 123.45567

OUTPUT:

123.46

缩短它可以做一些事情,比如:

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

hello 123.45 goodbye

这基本上是通过找到窗体 .dd[ddd...] (其中 d 是一个数字) 的字符串来工作的,并且只用 .dd (括号作用是捕捉 .ddd bit) 来取代整个事物。

ounding 它有点困难,因为它不是简单的文本替换(如果下一个数字为5或5以上,您必须 change 最后一个数字才能添加一个)。 您可能需要为此使用略微更适应性更强的工具。

一种 < / em > 方法可以做到这一点(虽然我敢肯定这不是最优 < / em > 方法), 是 < code> 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 "
"; 

hello 123.46 9876.54 goodbye

在每个符合理想模式的字段上都进行圆形操作, 但是,如上所述, 它非常丑陋—— 我相信有更好的方法(brian dfoy, where are you? )

既然还没有人能够使用 sed 进行四舍五入, 请在此以 Python 为例 :

$ 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

您可以将 2 换成其它东西来改变四舍五入的精确度 。





相关问题
Uncommon regular expressions [closed]

Recently I discovered two amazing regular expression features: ?: and ?!. I was curious of other neat regex features. So maybe you would like to share some tricky regular expressions.

regex to trap img tag, both versions

I need to remove image tags from text, so both versions of the tag: <img src="" ... ></img> <img src="" ... />

C++, Boost regex, replace value function of matched value?

Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

Is it possible to negate a regular expression search?

I m building a lexical analysis engine in c#. For the most part it is done and works quite well. One of the features of my lexer is that it allows any user to input their own regular expressions. This ...

regex for four-digit numbers (or "default")

I need a regex for four-digit numbers separated by comma ("default" can also be a value). Examples: 6755 3452,8767,9865,8766,3454 7678,9876 1234,9867,6876,9865 default Note: "default" ...