The next call to replace() will replace all trailing 0 and trailing . , if they are:
eval(expression).toPrecision(10).replace(/(?:\.0+|(\.\d+?)0+)$/, "$1")
How it works?
/(?:\.0+|(\.\d+?)0+)$/ searches for \.0+ or (\.\d+?)0+ at the end of the line ( $ ). ?: prevents \.0+|(\.\d+?)0+ from "capture" .
\.0+ will match . followed by any number 0 s.
(\.\d+?)0+ will match . followed by at least one digit, followed by at least one 0 . ? guarantees 0+ as large as 0 . The brackets "capture" are not 0 s.
The second replace() parameter is a new line to replace what was matched. $1 is a sorting variable and tells replace() to replace the matching value with the first committed value (since 1 was after $ ). In this case, the first recorded value was any \.\d+? .
So at the end:
. followed by any number 0 will be discarded. followed by not 0 , followed by 0 , will be reset to 0
Examples
For comparing methods for accuracy 1 , 2 and 3 for .40*1 , 4*1 and 40*1 see below. The first (bold) element in each group is the method. Red elements are those that do not meet expectations.
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>
source share