fix: 修复计算器计算加减乘除、平方、平方根等运算的精度问题

This commit is contained in:
cong_wang
2023-08-10 09:03:28 +08:00
parent 989fc25ce0
commit faa0656e71
3 changed files with 44 additions and 6 deletions
+3 -1
View File
@@ -1 +1,3 @@
web.config
web.config
.vscode
.idea
+5 -4
View File
@@ -1209,6 +1209,7 @@
</div>
<!-- partial -->
<script src='https://cdns.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js'></script>
<script src="https://unpkg.com/big.js@5.2.2/big.min.js"></script>
</div>
<div id="window-fill"></div>
<div class="window setting">
@@ -1465,8 +1466,8 @@
<div class="content" id="win-calc">
<input id="calc-input" value="" onkeydown="if(event.keyCode == 13)$('#win-calc>.keyb>.ans').click()">
<div class="keyb">
<a class="a b" onclick="$('#calc-input')[0].value*=$('#calc-input').val()">𝑥²</a>
<a class="a b" onclick="$('#calc-input').val(Math.sqrt($('#calc-input').val()))">√𝑥</a>
<a class="a b" onclick="calculateSquare()">𝑥²</a>
<a class="a b" onclick="calculateSquareRoot()">√𝑥</a>
<a class="a b" onclick="$('#calc-input')[0].value='0'">C</a>
<a class="a b u" onclick="apps.calc.add('+')">+</a>
<a class="a b" onclick="apps.calc.add('7')">7</a>
@@ -1487,7 +1488,7 @@
onclick="if($('#calc-input').val().length > 1) { $('#calc-input').val($('#calc-input')[0].value.substring(0,$('#calc-input')[0].value.length-1)); } else { $('#calc-input').val('0'); }"><i
class="bi bi-backspace"></i></a>
<a class="a b ans u"
onclick="$('#calc-input')[0].value=eval($('#calc-input')[0].value.replace('÷', '/').replace('×', '*'))">
onclick="calculate()">
=</a>
</div>
</div>
@@ -2676,4 +2677,4 @@
<script src="https://cdn.staticfile.org/ace/1.23.0/ext-error_marker.min.js"></script>
</body>
</html>
</html>
+36 -1
View File
@@ -3306,4 +3306,39 @@ if (!location.href.match(/((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|
}
function sendToSw(msg) {
navigator.serviceWorker.controller.postMessage(msg);
}
}
function calculate() {
let matches = $('#calc-input')[0].value.match(/([-+]?\d*\.?\d+)\s*([-+×÷])\s*([-+]?\d*\.?\d+)/);
if (matches) {
let operand1 = matches[1];
let operator = matches[2];
let operand2 = matches[3];
switch (operator) {
case '+':
$('#calc-input')[0].value = new Big(operand1).plus(operand2).toString();
break
case '-':
$('#calc-input')[0].value = new Big(operand1).minus(operand2).toString();
break
case '×':
case '*':
$('#calc-input')[0].value = new Big(operand1).times(operand2).toString();
break
case '÷':
case '/':
$('#calc-input')[0].value = new Big(operand1).div(operand2).toString();
break
}
}
}
function calculateSquare() {
let num = new Big($('#calc-input')[0].value)
$('#calc-input')[0].value = num.times(num).toString()
}
function calculateSquareRoot() {
let num = new Big($('#calc-input')[0].value)
$('#calc-input')[0].value = num.sqrt().toString()
}