使用 jquery 添加要显示为浮点格式的数字

我正在尝试添加金额以显示为,1.00但它显示为1。我尝试过使用toFixed(2)+ 1,但它只是停留在0.00. 有没有正确的方法来做到这一点,也许使用正则表达式?


var ex = "/^[0-9]+\.?[0-9]*$/";


$("#addDollar").on("click", function() {

  var valueOut = $("#totalAmountIn");

  valueOut.val(parseFloat(valueOut.val() + 1).toFixed(2));

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Total Amount In</h1>


<input type="text" value="0.00" id="totalAmountIn"></input>


<div class="col-md-4">

  <button type="button" id="addDollar" class="btn btn-default">

  Add Dollar

  </button>

</div>


潇潇雨雨
浏览 139回答 1
1回答

蓝山帝景

您需要先解析该值,然后再添加 1。您的代码是连接 1,然后解析。所以0.00变成0.001,当你打印出小数点后两位时,它又变成了0.00。var ex = "/^[0-9]+\.?[0-9]*$/";$("#addDollar").on("click", function() {&nbsp; var valueOut = $("#totalAmountIn");&nbsp; valueOut.val((parseFloat(valueOut.val()) + 1).toFixed(2));})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h1>Total Amount In</h1><input type="text" value="0.00" id="totalAmountIn"></input><div class="col-md-4">&nbsp; <button type="button" id="addDollar" class="btn btn-default">&nbsp; Add Dollar&nbsp; </button></div>var ex = "/^[0-9]+\.?[0-9]*$/";$("#addDollar").on("click", function() {&nbsp; var valueOut = $("#totalAmountIn");&nbsp; valueOut.val((parseFloat(valueOut.val()) + .25).toFixed(2));})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h1>Total Amount In</h1><input type="text" value="0.00" id="totalAmountIn"></input><div class="col-md-4">&nbsp; <button type="button" id="addDollar" class="btn btn-default">&nbsp; Add $0.25&nbsp; </button></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go