//判断a和b是不是小数 //如果是小数,就转换成整数,倍数是a1 ,b1 //将a和b作乘法 //将结果除以相应的倍数 function multiply(a, b) { var a1 = 1, b1 = 1; if(a != parseInt(a, 10)){ a1 = Math.pow(10, a.toString().length - 2); a = a * a1; } if(b != parseInt(b, 10)){ b1 = Math.pow(10, b.toString().length - 2); b = b * b1; } return a*b/(a1*b1); }
function multiply(a, b) { var str_a = a.toString(); var str_b = b.toString(); // *重要*: 取精度大的作为结果精度 var a_length = str_a.length - str_a.indexOf('.')-1; var b_length = str_b.length - str_b.indexOf('.')-1; var length = Math.max(a_length, b_length); return parseFloat(str_a * str_b).toFixed(length); }
function multiply(a, b) { var aStr = a + '' var bStr = b + '' //var pointLen = Math.max(aStr.length-aStr.indexOf('.')-1, bStr.length-bStr.indexOf('.')-1) var pointLen = aStr.length-aStr.indexOf('.')-1 + bStr.length-bStr.indexOf('.')-1 return parseFloat((a*b).toFixed(pointLen)) }
function multiply(a, b) {
}
function multiply(a, b) { var pointA = a.toString().indexOf('.'); var pointB = b.toString().indexOf('.'); var expendA = Math.pow(10,a.toString().length-pointA+1); var expendB = Math.pow(10,b.toString().length-pointB+1); return ((a*expendA)*(b*expendB))/(expendA*expendB); }
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));