当前位置: 首页 > 工具软件 > jsMath > 使用案例 >

js math.js 加减乘除 eval方式解决精度问题

太叔天宇
2023-12-01

js math.js 解决 加减乘除 精度问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta  http-equiv = "Content-Type" content = "text/html; charset=utf-8" />

<script type = "text/javascript" src="math.js"></script>
<script type = "text/javascript">

console.log( 0.02 - 0.03 ); // -0.009999999999999998
console.log( 1 - 0.8 );  // 0.19999999999999996 
console.log( 6 * 0.7 );  // 4.199999999999999 
console.log( 0.1 + 0.2 );  // 0.30000000000000004 
console.log( 0.1 + 0.7 );  // 0.7999999999999999 
console.log( 1.2 / 0.2 );  // 5.999999999999999 

// 使用 .eval() 高精度计算
math.config({
	number: 'BigNumber',  
	precision: 20         
});

//加
console.log(math.format(math.add(math.bignumber(0.1),math.bignumber(0.2)))) // 0.3
//减:
console.log( math.format(math.subtract(math.bignumber(0.02),math.bignumber(0.03))));
//乘:
console.log(math.format(math.multiply(math.bignumber(6),math.bignumber(0.7))));
//除:
console.log(math.format(math.divide(math.bignumber(1.2),math.bignumber(0.2))))
</script>
</head>
<body>

</body>
</html>
 
 类似资料: