分享、学习、提高
2008/04/22 17:26
Tags: ,
一个JS程序,需要取小数点后面两位。找了一下,没发现有这类函数,于是就这样写了一下。
function roundFun(strValue){
  strValue = strValue.toString();
  strValue = strValue.substr(0,strValue.indexOf(".")+3);
  return parseFloat(strValue);
}
这样写,倒是没什么问题。

但是无意中发现:alert(6.22+5),本来应该返回11.22,但是出来的确是11.2199999....,不知道是什么原因。
分别测试,6.22,6.22+1都是对的,6.22+4也就不对了。

朋友找了一下,发现有现成的toFixed函数。使用它后,9999的问题解决:)
但是toFixed返回的是字符串,如果需要再次计算的话,还要转一次,索性写了一个函数,调用更方便。
function roundFun(strValue){
  strValue = strValue.toFixed(2);
  return parseFloat(strValue);
}


后来,网上发现一个这样的函数,感觉更好,就用它了。http://code.itlearner.com/javascript/formatFloat.html
function formatFloat(src, pos)
{
    return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);
}
alert(formatFloat("1212.1222", 2));


分页: 1/1 第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]