我正在使用JavaScript创建一个在线计算器。
我有这个来计算。
eval(expression).toPrecision(10);
这几乎在所有情况下都能产生正确的输出。例如
eval('456456+45646486*45646884').toPrecision(10)
// Output: "2.083619852e+15"
eval('1/0').toPrecision(10)
// Output: "Infinity"
但是,我的计算结果是这样的:在几乎所有的情况下,这都会产生正确的输出。
eval('4*1').toPrecision(10)
// Output: "4.000000000"
如何修剪尾部的零?不过 也保持上面的漂亮输出?
只有全零小数
eval('4*1').toPrecision(10).replace(/\.0+$/,"")
零结束的小数。
eval('4.5*1').toPrecision(10).replace(/\.([^0]+)0+$/,".$1")
编辑:同时处理所有零和零末尾的情况。
EDIT: 如果你总是先使用.toPrecision(),因此总是有一个".",你可以修剪掉任何尾部的零。
eval('4.5*1').toPrecision(10).replace(/0+$/,"")
EDIT:处理尾部的小数,在使用toPrecision.toPrecision()后除以1。
eval('4.5*0').toPrecision(10).replace(/\.?0+$/,"")
在使用toPrecision.Javascript除以1后,将尾随0,而不需要使用regexes。
下面是 replace()
调用将替换所有尾部的 0
和尾部的 .
如果存在的话。
eval(expression).toPrecision(10).replace(/(?:\.0+|(\.\d+?)0+)$/, "$1")
/(?:\.0+|(\.\d+?)0+)$/
寻找 \.0+
或 (\.\d+?)0+
在字符串末尾 ($
). 该 ?:
防止 \.0+|(\.\d+?)0+
从被 "捕获".
\.0+
将匹配 .
后面是任意数量的 0
s.
(\.\d+?)0+
将匹配 .
后面是至少一个数字,后面是至少一个 0
. 该 ?
确保 0+
尽可能多地匹配 0
的,尽可能的。括号中 "捕捉 "到的非0
s.
上的第二个参数 replace()
是新的字符串,用来替换匹配的内容。该 $1
是一个变量,告诉 replace()
用第一个捕获的值替换匹配的值(因为 1
是在之后 $
). 在这种情况下,第一个捕获的值是不管是什么 \.\d+?
匹配。
所以,最后。
.
后面是任意数量的 0
将被丢弃.
其次是非0
随后是 0
将有 0
弃用用于比较以下方法的精密度: 1
, 2
和 3
对于 .40*1
, 4*1
和 40*1
,见下文。每组中第一项(粗体)是本方法。红色项目是不符合预期的项目。
var tests = [
'.04*1',
'.40*1',
'4*1',
'40*1'
];
var results = {};
for (var i = 0; i < tests.length; i += 1) {
results[i] = {};
for (var p = 1; p < 3; p += 1) {
results[i][p] = {};
results[i][p][0] = {
'output': eval(tests[i]).toPrecision(p).replace(/(?:\.0+|(\.\d+?)0+)$/, "$1"),
'regex': '/(?:\.0+|(\.\d+?)0+)$/, "$1"'
};
results[i][p][1] = {
'output': eval(tests[i]).toPrecision(p).replace(/\.0+$/, ""),
'regex': '/\.0+$/, ""'
};
results[i][p][2] = {
'output': eval(tests[i]).toPrecision(p).replace(/\.([^0]+)0+$/, ".$1"),
'regex': '/\.([^0]+)0+$/, ".$1"'
};
results[i][p][3] = {
'output': eval(tests[i]).toPrecision(p).replace(/0+$/, ""),
'regex': '/0+$/, ""'
};
results[i][p][4] = {
'output': eval(tests[i]).toPrecision(p).replace(/\.?0+$/, ""),
'regex': '/\.?0+$/, ""'
};
}
}
for (var i in results) {
$("#result").append("<h1>" + tests[i] + "</h1>");
for (var p in results[i]) {
var expected = null;
for (var t in results[i][p]) {
var div = $("<div></div>");
if (t == 0) {
expected = results[i][p][t].output;
div.addClass("expected");
} else if (results[i][p][t].output !== expected) {
div.addClass("invalid");
}
div.append("P" + p + ": " + results[i][p][t].output);
div.append(" <small>" + results[i][p][t].regex + "</small>");
$("#result").append(div);
}
$("#result").append("<br>");
}
}
body { font-family: monospace; }
.expected { font-weight: bold; }
.invalid { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>