<!DOCTYPE html>
<html lang="en">
<head> </head>
<body translate="no">
<input type="number" placeholder="user enter's here" name="price" id="get" />
<input type="number" name="reduced" value="0.0039" id="qty_1" />
<input type="number" placeholder="output" name="total" id="send" readonly />
<script src="https://cpwebassets.codepen.io/assets/common/stopExecutionOnTimeout-1b93190375e9ccc259df3a57c1abc0e64599724ae30d7ea4c6877eb615f89387.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script id="rendered-js">
$(function () {
$("#get, #reduced").keyup(function () {
var input = $("#get").val() || 0;
var input2 = $("#reduced").val() || 0;
$("#send").val(input - input2);
});
});
//# sourceURL=pen.js
</script>
</body>
</html>
我确实有一个代码,它减去用户输入的金额,当用户输入一个十进制数时,它会显示很长的数字。我如何将其缩短为两位?我尝试添加.tofixed(2)
,其他都不起作用。
您可以使用toFixed((
//...
var price = parseFloat($("#price_1").val()).toFixed(2);
var qty = parseFloat($("#qty_1").val()).toFixed(2);
//...
试试下面的代码,它还考虑了输入中输入了无效数字的情况:
$("#get, #reduced").keyup(function () {
var input = parseFloat($("#get").val()) || 0.0;
var input2 = parseFloat($("#reduced").val()) || 0.0;
var result = parseFloat(input - input2).toFixed(2)
$("#send").val(result);
});
希望能有所帮助。