Popular Posts

Tags

工商服務


以數學的原理處理「四捨五入」

我看過太多人都把四捨五入的問題看成是「字串」來處理,實際上,如果把四捨五入做為「數學」來解的話,程式大概只要幾行即可解決。

以四捨五入取整數的例子來講,其原理就是: 任何數值+0.5 再取整數

但要注意的是,當四捨五入遇到「負數」時,處理的方式就會變成「五捨六入」,這是因為中間數要往數值大的那邊進位的緣故。所以加上了負數的處理,程式至少又多了一行:

Perl 的四捨五入

sub round{
  my($value,$rank) = @_;
  if($value>0){
    return ( int($value * 10**$rank) + 0.5 ) / 10**$rank;
  }else{
    return ( int($value * 10**$rank) - 0.4 ) / 10**$rank;
  }
}
print round(12.345 , 2);

round() 函式的第一個參數為欲轉換的數值,第二個參數為欲取得的小數點位數

Javascript 的四捨五入

<script type='text/javascript'>
//方法一
function round1(value,rank){
  if(value >= 0){
    return parseInt(value * Math.pow(10,rank) + 0.5) / Math.pow(10,rank);
  }else{
    return parseInt(value * Math.pow(10,rank) - 0.4) / Math.pow(10,rank);
  }
}
//方法二: 使用內建的 round 數學函數
function round2(value,rank){
  return Math.round(value * Math.pow(10,rank)) / Math.pow(10,rank);
}
document.write(round1(12.345 , 2) + "<br />");
document.write(round2(12.345 , 2));
</script>

round1() 及 round2() 函式的第一個參數為欲轉換的數值,第二個參數為欲取得的位數



3 Responses to “以數學的原理處理「四捨五入」”

  1. Using Mozilla Firefox Mozilla Firefox 3.0 on Windows Windows Vista

    很不錯的文章

    像有些語言提供現成的round(),其實是『四捨六入五成雙』
    判斷方式就有點小差異


  2. Using Mozilla Firefox Mozilla Firefox 2.0.0.16 on Windows Windows XP

    負數的處理有點問題喔。還是要減0.5才對。


  3. Using Internet Explorer Internet Explorer 8.0 on Windows Windows XP

    呵呵,0.5中间值


Post a Comment



  • 彙整

  • 分類

  • 其它

Content

我們解決了什麼問題?我們創造了什麼價值?