输入到我的函数值的2个数字是a, "0.045u"
和b, "3"
function mult2nums(a,b) {
var c = null;
var unitsFora = null;
var unitsForb = null;
var cUnits = null;
//--> issue - unitsFora = ??; // how to strip off units designator
//--> issue - unitsForb = ??; // how to strip off units designator
a = isFloat(a); // also works if int
b = isFloat(b); //
c = a*b;
// add logic to compare unit designators and convert as needed
return(c+cUnits); // need to return the units, returns a string type
}
答案 0 :(得分:0)
您可以使用正则表达式过滤单位:
function mult2nums(a,b) {
var c = null;
var cUnits = null;
var unitRegex = /[A-Za-z].*/g
var unitsForA = a.match(unitRegex);
var unitsForB = b.match(unitRegex);
a = parseFloat(a.replace(unitsForA, ''));
b = parseFloat(b.replace(unitsForB, ''));
c = a*b;
// add logic to compare unit designators and convert as needed
return c + cUnits;
}
请注意,代码使用第一次遇到的字符作为单位的起始位置。它可以处理大小写差异,以及包含数字的单位(例如m / s ^ 2)。您可以进一步修改代码以满足您的特定需求。
jsFiddle示例: https://jsfiddle.net/ywafx1be/