[Perl][JavaScript]以数学的原理处理四舍五入

我看过太多人都把四舍五入的问题看成是“字串”来处理,实际上,如果把四舍五入做为“数学”来解的话,程式大概只要几行即可解决。

以四舍五入取整数的例子来讲,其原理就是: 任何数值 +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);
}
//方法三: 使用内建的 toFixed() 函数 (传回字串)
function round3(value, rank){
  return Number.parseFloat(value).toFixed(rank);
}
console.log(round1(12.345, 2)); // 12.35
console.log(round2(12.345, 2)); // 12.35
console.log(round3(12.345, 2)); // "12.35"
</script>

这三个自订函式的第一个参数为欲转换的数值,第二个参数为欲取得的位数

    • 晴树
    • 08/21. 2008 9:29上午
    Using Mozilla Firefox Mozilla Firefox 3.0 on Windows Windows Vista

    很不错的文章

    像有些语言提供现成的round(),其实是‘四舍六入五成双’
    判断方式就有点小差异

    • cvictor
    • 08/26. 2008 12:38上午
    Using Mozilla Firefox Mozilla Firefox 2.0.0.16 on Windows Windows XP

    负数的处理有点问题喔。还是要减0.5才对。

    • 小迪
    • 10/12. 2011 4:24下午
    Using Internet Explorer Internet Explorer 8.0 on Windows Windows XP

    呵呵,0.5中间值

  1. No trackbacks yet.

return top

%d 位部落客按了赞: