Home > Web Front-end > JS Tutorial > js implements the multiplication and division functions of two decimals

js implements the multiplication and division functions of two decimals

巴扎黑
Release: 2016-12-06 10:12:14
Original
2098 people have browsed it

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>jquery中的ajax</title> 
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> 
<style type="text/css"> 
</style> 
<script type="text/javascript"> 
//计算两个数相乘 
function Mul(arg1, arg2){ 
var m=0,s1=arg1.toString(),s2=arg2.toString(); 
//获取两个相乘数据的小数点后面的数据的长度,即获取小数的位数,因为最终相乘计算的结果:结果小数的位数=第一个数的小数位数+第二个数的小数位数 
     try{ 
      m+=s1.split(".")[1].length; 
    }catch(e){} 
     try{ 
      m+=s2.split(".")[1].length; 
    }catch(e){} 
    //将两个小数去掉小数点,强制转换整个值(即进行数值放开小数点位数的倍数),然后进行相乘的操作,相乘的结果除去10的m次方 
     return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m); 
} 
//计算两个数相除 
function  division(arg1, arg2){ 
var t1 = 0, t2 = 0, r1, r2; 
     try { 
      t1 = new String(arg1).split(".")[1].length; 
    } catch (e) { } 
     try { 
      t2 = arg2.toString().split(".")[1].length; 
    } catch (e) { } 
     r1 = Number(new String(arg1).replace(".", "")); 
     r2 = Number(arg2.toString().replace(".", "")); 
     //放大倍数后两个数相除 后,乘以两个小数位数长度相减后的10的次幂 
     var money = Mul((r1 / r2),Math.pow(10, t2 - t1)); 
     //保留2个小数位数 
     return money.toFixed(2); 
} 

$(function(){ 
alert(Mul(1.414,1.732)); 
alert(division(1.732,1.4146)); 
}); 
</script> 
</head> 
<body> 
</body> 
</html>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template