3

我正在为工程模拟编写一个基于 Web 的前端。后端仅接受无前缀 SI 单位的值,例如米或瓦特。然而,最好允许用户以他们希望的任何单位输入值。例如,如果您需要输入距离,您可以输入:

15 inches
3.1 meter
1.4 km

但值如下:

12 seconds
5 pounds
147 watts

会被拒绝。我第一次尝试使用js-quantities,但它没有以最直观的方式解析派生单位。它需要在每个相乘单位之间放置一个空间。例如,以安培小时为单位输入电量100 Ah是无效的,但100 A h可以接受。此外,js-quantities 不支持扭矩或温度单位(仅支持温差,例如,您不能将华氏温度转换为摄氏度)

然后我尝试使用谷歌计算器 API 进行单位转换,但它会产生难以解析小数字的结果:

将 5 nm 转换为米

要求:

http://www.google.com/ig/calculator?hl=en&q=5%20nm=?m

回复:

{lhs: "5 nanometers",rhs: "5.0 \x26#215; 10\x3csup\x3e-9\x3c/sup\x3e meters",error: "",icc: false}
4

3 回答 3

2

在我看来,修改 js-quantities 会相当容易。

您只需编辑函数 parse(val) 函数。您尝试解析,失败后您只需按照非常简单的规则集的要求插入空格。您从左到右遍历字符串并识别单位并拆分字符串。

但是,我可能会采用另一种解决方案,在用户输入它时已经将其拆分(通过相同类型的规则)。这样,当用户输入一个值时,它可以显示 Ah 的“使用安培小时数”,并且用户可以看到一切都是他想要的方式。这样,如果不是他的意思,您可以让用户从列表(或更高级的构建器)中进行选择。

于 2013-10-04T09:39:21.777 回答
0

Have you looked at mathjs?

http://mathjs.org/

It doesn't have derived units yet (I don't believe) but they are working on it. Other than that it's probably the closest thing to what you want.

If you need more functionality specific to your industry of engineering, you'll need to extend a library at some point.

于 2013-10-10T12:32:31.550 回答
0

Google 计算器的输出似乎并不难解析。

我会做这样的事情:

//Parse JSON output to JS variables
    ret = JSON.parse(JSON.stringify({lhs: "5 nanometers",rhs: "5.0 \x26#215; 10\x3csup\x3e-9\x3c/sup\x3e meters",error: "",icc: false} ));

  //ret = Object {lhs: "5 nanometers", rhs: "5.0 &#215; 10<sup>-9</sup> meters", error: "", icc: false}
  var lhs = new Object();
  //Check if lhs has exp notation 
  if (ret.lhs.search("&#215; ")!==-1) {
  //If so, conversion is a bit harder...but not much
  temp = ret.lhs.split("&#215; ");  
  lhs.base = temp[0]

  temp = temp[1].split("<sup>")[1].split("</sup>");
  lhs.exp = temp[0];
  lhs.unit = temp[1];
  lhs.num = parseFloat(lhs.base)*Math.pow(10,parseFloat(lhs.exp));
} else {
  //If no, piece of cake
  temp = ret.lhs.split(" ");  
  lhs.num = parseFloat(temp[0]);
  lhs.unit = temp[1];
}

//Exactly the same for rhs
var rhs = new Object();    
if (ret.rhs.search("&#215; ")!==-1) {

  temp = ret.rhs.split("&#215; ");  
  rhs.base = temp[0]

  temp = temp[1].split("<sup>")[1].split("</sup>");
  rhs.exp = temp[0];
  rhs.unit = temp[1];
  rhs.num = parseFloat(rhs.base)*Math.pow(10,parseFloat(rhs.exp));

} else {
  temp = ret.lhs.split(" ");  
  lhs.num = parseFloat(temp[0]);
  lhs.unit = temp[1];
}

console.log("Converted",lhs.num,lhs.unit,"to",rhs.num,rhs.unit);

输出:将 5 纳米转换为 5e-9 米

由于您现在将 lhs 和 rhs 作为数字 javascript 变量并将它们的单位作为字符串,因此您可以随意格式化/处理它们。

于 2013-10-06T18:09:17.187 回答