[英]JavaScript: Trim .toPrecision() trailing zeros
我正在使用 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"
如何修剪尾隨零但同時保持上面的良好輸出?
使用 toPrecision 后除以 1。 Javascript 將跟蹤零,並且不需要正則表達式。
只有全零小數
eval('4*1').toPrecision(10).replace(/\.0+$/,"")
零結尾小數:
eval('4.5*1').toPrecision(10).replace(/\.([^0]+)0+$/,".$1")
編輯:處理所有零和結束零的情況
編輯:如果您總是首先使用 .toPrecision(),因此總是有一個“.”,您可以修剪掉任何尾隨零:
eval('4.5*1').toPrecision(10).replace(/0+$/,"")
編輯:處理尾隨小數:
eval('4.5*0').toPrecision(10).replace(/\.?0+$/,"")
下面的replace()
調用將替換所有尾隨0
和尾隨.
,如果存在:
eval(expression).toPrecision(10).replace(/(?:\.0+|(\.\d+?)0+)$/, "$1")
/(?:\\.0+|(\\.\\d+?)0+)$/
在字符串 ( $
) 的末尾查找\\.0+
或(\\.\\d+?)0+
。 ?:
防止\\.0+|(\\.\\d+?)0+
被“捕獲” 。
\\.0+
將匹配.
后跟任意數量的0
秒。
(\\.\\d+?)0+
將匹配.
后跟至少一位數字,后跟至少一位0
。 ?
確保0+
匹配盡可能多的0
。 括號“捕獲”了非0
秒。
replace()
的第二個參數是替換匹配內容的新字符串。 $1
是一個排序變量,它告訴replace()
用第一個捕獲的值替換匹配的值(因為1
在$
)。 在這種情況下,第一個捕獲的值是\\.\\d+?
匹配。
所以,最后:
.
后跟任意數量的0
將被丟棄.
后跟非0
s 后跟0
s 將丟棄0
s有關.40*1
、 4*1
和40*1
精度為1
、 2
和3
的方法的比較,請參見下文。 每組中的第一個(粗體)項目是這種方法。 紅色項目是那些不符合預期的項目。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.