function multiply(a, b) { var a = a; var b = b; if(isInteger(a)&&isInteger(b)){ return a * b; }else{ var ad = a.toString().split(".").length > 1 ? a.toString().split(".")[1].length:0; var bd = b.toString().split(".").length > 1 ? b.toString().split(".")[1].length:0; return (a * b).toFixed(ad+bd); } function isInteger(num){ if(parseInt(num)===num){ return true; }else{ return false; } } }
function multiply(a, b) {
function getDecimalLength(x) {
var str = x.toString();
var index = str.indexOf('.');
return index == -1 ? 0 : str.length - index - 1;
}
var decimalLength = getDecimalLength(a) + getDecimalLength(b);
var ans = a * b;
ans = ans.toFixed(decimalLength);
ans = parseFloat(ans.toString());
return ans;
}
先将小数用10的n次方转化成整数,乘完的结果在除以之前乘了多少个10 function multiply(a, b) { a = a.toString(); b = b.toString(); var aLen = a.substring(a.indexOf(".")+1).length; var bLen = a.substring(a.indexOf(".")+1).length; return (a * Math.pow(10,aLen)) * (b * Math.pow(10,bLen)) / Math.pow(10,aLen+bLen); }
function multiply(a, b) {
}
function multiply(a, b) { var strA = ''+a; var strB = ''+b; var lenA = (strA.indexOf('.')==-1)?0:(strA.length-strA.indexOf('.')-1); var lenB = (strB.indexOf('.')==-1)?0:(strB.length-strB.indexOf('.')-1); var len = lenA+lenB var result = (a*b).toFixed(len); return result; }
function multiply(a, b) { // 先将数字转换为字符串 var strA=""+a; console.log(strA); var strB=""+b; console.log(strB); // 先获取两个数的小数位数 var lenA=(strA.indexOf(".")==-1)?0:(strA.length-strA.indexOf(".")-1); var lenB=(strB.indexOf(".")==-1)?0:(strB.length-strB.indexOf(".")-1); // 比较两数的精度,精度大的作为结果数精度 len=Math.max(lenA,lenB); console.log("lenA "+lenA+"\t"+"lenB "+lenB+"\n"); // 计算运算结果 var result=null; result=parseFloat(a*b).toFixed(len); console.log("float "+result+"\n"); return result; } 如何将数字原原本本的转换为字符串(例如 3.01->> "3.01")
function len(num) { var str = num.toString(); var index = str.indexOf('.'); return index == -1 ? 0 : str.length - index - 1; } function solution(a, b) { var length = Math.pow(10, len(a) +len(b)); return a * length * b / length; } console.log(solution(0, 0.001)); console.log(solution(0.001, 0.001)); console.log(solution(3, 0.001)); console.log(solution(1000, 0.001));
function multiply(a, b) { var a1=a*10000; var b1=b*10000; var temp = a1*b1; var result = temp/100000000; return result }比较野蛮的方法 大家应该一看就懂
function multiply(a, b) { let [len1,len2] = [1,1]; if(String(a).indexOf('.') != -1) { len1 = String(a).length - String(a).indexOf('.') -1; len1 = Math.pow(10,len2); a = a*len1; } if(String(b).indexOf('.') != -1) { len2 = String(b).length - String(a).indexOf('.') -1; len2 = Math.pow(10,len2); b = b*len2; } return (a*b)/(len1*len2); }js中,小数相乘由于精度问题,会出现误差,避免的方式是先将小数都变成整数,相乘后再除以放大的倍数,就不会出现精度问题带来的误差了
function multiply(a, b) { var x,y; try{ x = a.toString().split(".")[1].length; }catch(e){ x = 0; }; try{ y = b.toString().split(".")[1].length; }catch(e){ y = 0; }; return ((a*Math.pow(10,x))*(b*Math.pow(10,y))) / Math.pow(10,x+y); }