今天有个妹纸问了小Z一个前端JS的问题,是java后端接口返回20位的两位金额小数,发现使用parsefloat转换会有精度丢失的情况,小Z觉得是JS的数位长度限制的问题,所以按照妹纸的需求,设计一个JS函数,将被加数、加数分别拆成低位数、高位数(长度小于等于10位),然后判断低位数相加,长度如果大于10,则高位数之和加一,js代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>my js test</title>
<style>
</style>
</head>
<body style="margin:0px;border:0px">
<style>
#myelement {
position: absolute;
left: 50px;
right: 100px;
}
</style>
<p title="testone" id="myelement">this is my element</p>
<script>
//第一组测试数据
<!-- var firstNumber = '123856789123456789.45'; -->
<!-- var secondNumber = '123456789123456789.45'; -->
//第二组测试数据
var firstNumber = '12385678910.23';
var secondNumber = '12345678910.12';
//第三组测试数据
<!-- var firstNumber = '12a345678910.23'; -->
<!-- var secondNumber = '12345678910.12'; -->
var r = largeNumberSum(firstNumber,secondNumber);
alert(r);
function largeNumberSum(a,b){
if(isNaN(Number(a))|| isNaN(Number(b)))
{
return null;
}
//根据需求,后台接口返回了20位的数,所以将被加数、加数分别拆成低位数、高位数(长度小于等于10位)
var num1 = a.replace('.','');//先去掉小数点
var num1Low = num1.substring(num1.length-10,num1.length);
var num1High = num1.substring(0,num1.length-10);
var num2 = b.replace('.','');
var num2Low = num2.substring(num2.length-10,num2.length);
var num2High = num2.substring(0,num2.length-10);
var lowAddResult = parseFloat(num1Low) + parseFloat(num2Low);
var highAddResult = parseFloat(num1High) + parseFloat(num2High);
//低位数相加,长度大于10,则高位数相加的结果加一
if(lowAddResult.toString().length>10){
highAddResult += 1;
}
var tempResult = highAddResult.toString() + lowAddResult.toString().substring(1,lowAddResult.toString().length);
//加入小数点
var result = tempResult.substring(0,tempResult.length - 2) +'.'+tempResult.substring(tempResult.length-2,tempResult.length);
return result;
};
</script>
</body>
</html>
先简单的实现特定的需求,这一类型的大数求和问题还要再研究研究。