js中数字计算精度(经测试,比较好)
2010-10-11 10:38
267 查看
------------------------------
/*
* 数值简单运算精度修正函数
* m 数值1(number)
* n 数值2(number)
* op 操作符(string)
*/
function fixMath(m, n, op) {
var a = (m+"");
var b = (n+"");
var x = 1;
var y = 1;
var c = 1;
if(a.indexOf(".")>0) {
x = Math.pow(10, a.length - a.indexOf(".") - 1);
}
if(b.indexOf(".")>0) {
y = Math.pow(10, b.length - b.indexOf(".") - 1);
}
switch(op)
{
case '+':
case '-':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
break;
case '*':
c = x*y
m = Math.round(m*x);
n = Math.round(n*y);
break;
case '/':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
c = 1;
break;
}
return eval("("+m+op+n+")/"+c);
}
用法如下:
-----------------------
fixMath(2.3, 1.9, '*')
fixMath(1.98, 1.9, '-')
fixMath(83.50, 74.15, '-')
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xjdawu/archive/2007/09/27/1803204.aspx
/*
* 数值简单运算精度修正函数
* m 数值1(number)
* n 数值2(number)
* op 操作符(string)
*/
function fixMath(m, n, op) {
var a = (m+"");
var b = (n+"");
var x = 1;
var y = 1;
var c = 1;
if(a.indexOf(".")>0) {
x = Math.pow(10, a.length - a.indexOf(".") - 1);
}
if(b.indexOf(".")>0) {
y = Math.pow(10, b.length - b.indexOf(".") - 1);
}
switch(op)
{
case '+':
case '-':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
break;
case '*':
c = x*y
m = Math.round(m*x);
n = Math.round(n*y);
break;
case '/':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
c = 1;
break;
}
return eval("("+m+op+n+")/"+c);
}
用法如下:
-----------------------
fixMath(2.3, 1.9, '*')
fixMath(1.98, 1.9, '-')
fixMath(83.50, 74.15, '-')
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xjdawu/archive/2007/09/27/1803204.aspx
相关文章推荐
- js中数字计算精度(经测试,比较好)
- js中数字计算精度
- JS数字计算精度误差解决方法
- js中数字计算精度
- js中数字计算精度
- js中数字计算精度
- JS数字计算精度误差的解决方法
- JS中数字计算精度
- JS中数字计算精度
- js计算精度问题
- javascript避免数字计算精度误差的方法之一
- JS精度计算 (转帖,补充减法)
- js 计算精度问题,及解决办法
- js数字计算 误差问题的快速解决方法
- javascript(js)浮点数字精度问题的一个解决办法。
- js数字位数太大导致参数精度丢失问题
- 将数字转化成一定精度的小数(JS函数)
- 数字倒数跳转的js代码(已测试通过)
- js浮点数精度问题(js计算中遇到的坑)
- 读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。 输出格式:在一行内输出n的各位数字之和