2013-04-09 43 views
2

我想用awk在bash中舍入幾個十進制值。例如:如果值是6.79如何四捨五入一個值,但不是在單位步驟

awk 'BEGIN {rounded = sprintf("%.0f", 6.79); print rounded }' 

這將返回我7

有沒有一種方式,我可以四捨五入不最接近的整數(1,2,3,...),但在步驟0.5(0,0.5,1,1.5,2,2.5 ...)

任何替代方式工作在Python或Perl也很好。目前在python

方式
python -c "from math import ceil; print round(6.79)" 

也回到7.0

回答

5

Perl的解決方案:

perl -e 'print sprintf("%1.0f",2 * shift)/2' -- 6.79 
7 

訣竅很簡單:乘以二的數量,圓它,分裂了。

+0

+1非常好的把戲,恭喜! – fedorqui 2013-04-09 13:16:29

+0

那真是太棒了.. thnx – marc 2013-04-09 13:21:16

0

這是一個通用的子程序,用於以給定的精度對最接近的值進行舍入: 我給出了一個需要舍入的例子,即0.5,我已經測試過它,即使負浮點數

#!/usr/bin/env perl 
use strict; 
use warnings; 

for(my $i=0; $i<100; $i++){ 
    my $x = rand 100; 
    $x -= 50; 
    my $y =&roundToNearest($x,0.5); 
    print "$x --> $y\n"; 
} 
exit; 

############################################################################ 
# Enables to round any real number to the nearest with a given precision even for negative numbers 
# argument 1 : the float to round 
# [argument 2 : the precision wanted] 
# 
# ie: precision=10 => 273 returns 270 
# ie: no argument for precision means precision=1 (return signed integer) => -3.67 returns -4 
# ie: precision=0.01 => 3.147278 returns 3.15 

sub roundToNearest{ 

    my $subname = (caller(0))[3]; 
    my $float = $_[0]; 
    my $precision=1; 
    ($_[1]) && ($precision=$_[1]); 
    ($float) || return($float); # no rounding needed for 0 

    # ------------------------------------------------------------------------ 
    my $rounded = int($float/$precision + 0.5*$float/abs($float))*$precision; 
    # ------------------------------------------------------------------------ 

    #print "$subname>precision:$precision float:$float --> $rounded\n"; 

    return($rounded); 
}