const reg = /^([0-9]+)\.([0-9]*)$/; // 判断是不是浮点数 const isFloat = function(number){ return reg.test(number); } // 去除小数点转为整数 const floatToInt = function(head,tail){//head:String tail:String // head和tail都是字符串 Number("005")可以去零 let result = head + Number(tail); return Number(result);//处理head为0的情况 } // 小数点后的长度e-n n为多少 const tailLen = function(tail){//tail:String return tail.length; } // 匹配数组包含了小数点左右两边的数据 const handlerFloat = function(float){//float:Float return reg.exec(float); } // 非浮点数的情况下判断传入的数据类型是否为合理数据 const canHandler = function(data){ let toString = Object.prototype.toString; let isNaN = data => typeof data=== ‘number‘ && data !== + data; let isBoolean = data === true || data === false || toString.call(data) === "[object Boolean]"; let isNull = data === null; let isUndefined = data === void 0; let isNumber = typeof data === ‘number‘ || toString.call(data) === "[object Number]"; let isString = typeof data === ‘string‘ || toString.call(data) === "[object String]"; if(isNaN(data) || isBoolean || isNull || isUndefined){ // throw new Error("only Number or String type"); console.log("only Number or String type"); return false; } return isNumber || (isString && !isNaN(Number(data))); } // API const floatMult=function(f1,f2){ if(isFloat(f1) && isFloat(f2)){ var eNum1,eNum2,match1,match2,int1,int2; // 匹配数组 match1 = handlerFloat(f1); match2 = handlerFloat(f2); //小数点后 这里用于转为科学计数法 eNum1 = match1[2].length; eNum2 = match2[2].length; // 去掉小数点 转为整数 int1 = floatToInt(match1[1],match1[2]); int2 = floatToInt(match2[1],match2[2]); // 0.2*0.3 = 2*3*(e-2) = (2*3)/100 return (int1*int2)/(Math.pow(10,(eNum1+eNum2))); }else{ return canHandler(f1) && canHandler(f2) && f1 * f2 ; } } // 暴露接口 module.exports = floatMult; console.log(floatMult(0.2,0.3));//0.06 console.log(floatMult(1.3,1.2));//1.56 console.log(floatMult(123.4,6456.3));//796707.42 console.log(floatMult(.2,.3));//0.06 console.log(floatMult(1,0.3));//0.3 console.log(floatMult(12,55));//660 console.log(floatMult("0.2","0.3"));//0.06 console.log(floatMult("0.2",0.3));//0.06 console.log(floatMult("12","25"));//300 console.log(floatMult("12",55));//660 console.log(floatMult("1.3.3",1.3));//false console.log(floatMult(true,0.3));//false "only Number or String type" console.log(floatMult(null,0.2));//false "only Number or String type" console.log(floatMult(void 0,0.3));//false "only Number or String type"
时间: 2024-12-18 01:14:34