Skip to content

Instantly share code, notes, and snippets.

@jorben
Created April 11, 2014 05:24
Show Gist options
  • Save jorben/10442212 to your computer and use it in GitHub Desktop.
Save jorben/10442212 to your computer and use it in GitHub Desktop.
javascript 浮点数操作出各种问题,比如0.1+0.2结果不等于0.3。而toFixed方法似乎也不是严格遵循四舍六入五留双,比如0.295.toFixed(2)的结果不是0.30
/**
* FPOperation: 浮点数操作
* 优点:自动计算原数据精确位数
* @param {Number} x
* @param {Number} y
* @param {String} operator
**/
function FPOperation(x, y , operator) {
if (!operator) {
return ;
}
var _m = 0 ,
xDigit = 0,
yDigit = 0;
try { xDigit = (x+'').split('.')[1].length; }catch (e){}
try { yDigit = (y+'').split('.')[1].length; }catch (e){}
_m = Math.pow(10, Math.max(xDigit, yDigit));
var _x = x * _m,
_y = y * _m ;
var ret ;
if (operator === '+') {
ret = _x + _y ;
}else if (operator === '-'){
ret = _x - _y ;
}else if (operator === '*'){
ret = _x * _y ;
}else if (operator ==='/'){
ret = _x / _y ;
}
return ret/_m;
}
/**
* toRound : 四舍五入版的toFixed
* 优点:保持了toFixed的数据结果风格,其实就是不足位则补0
* @param {Number} v 需要toFixed的数值 比如0.2950
* @param {Number} l 需要toFixed的位数 比如2
**/
function toRound(v,l){ return (Math.round(v*Math.pow(10, l))/Math.pow(10, l)).toFixed(l); }
@jorben
Copy link
Author

jorben commented Apr 11, 2014

两个方法都可以,看需求使用
调用示例:
FPOperation(0.1, 0.2, '+');
// result: 0.3

toRound(0.1+0.2, 2)
// result: "0.30"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment