星期四, 三月 02, 2006

Perl 四捨五入

方法1: 自己寫 round()

sub round {
    my $val = shift;
    my $col = shift;
    my $r = 10 ** $col;
    my $a = ($val > 0) ? 0.5 : -0.5;
    return int($val * $r + $a) / $r;
}
# 於要取的位數後 +0.5, 再取整數即可.
my $a = 10.335444;
print round($a, 2);

方法2: 使用 sprintf()

my $a = 10.335444;
print sprintf("%.2f", $a);

用法可參考: Perl 5.8.0 Documentation - sprintf

相關標籤

this is comment icon Perl自己沒有四捨五入的函數??? [回覆]

感覺很基本的東西竟然沒有@@

Comment by 米開朗基羅 (11/23/2006 20:08)

this is comment icon 回 米開朗基羅 [回覆]

我是找不到 Perl 四捨五入的函式在哪邊, 所以不得已才寫這個囉~~
還是長輩能告知此函式的名稱是???

Comment by Tsung (11/24/2006 08:26)

this is comment icon [回覆]

參考這篇 http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
perl沒有內建的round函數

Comment by jck11 (06/26/2007 00:03)

this is comment icon 回 jck11 [回覆]

原來如此, 而且連 function 都寫好了, 感恩 Orz...

Comment by Tsung (06/26/2007 00:25)

this is comment icon int [回覆]

perldoc -f int

Comment by bash99 (01/11/2008 14:33)

this is comment icon 回 bash99 [回覆]

int ???

Comment by Tsung (01/11/2008 15:08)
Add this page to del.icio.us Add this page to Yahoo Taiwan's bookmark Add this page to MyShare

發表迴響

標題

內容 (限制 1000 字)

暱稱

電子郵件

個人網頁


 authimage


PS: 若無法留言, 請先確認是否有打開 JavaScript, 造成您的困擾, 實在萬分對不起 Orz...(如果無法留言, 勞煩可以發信給我好嗎? 謝謝.)
PS2: 若您的留言被誤判, 我都會再自行看過, 不需要一直重覆張貼~