[英]JS adding two numbers and displaying to two decimal places
The code I currently have is able to take a number from a text field and do a calculator however I cant get the numbers to display to two decimal places:.我目前拥有的代码能够从文本字段中获取一个数字并做一个计算器,但是我无法将数字显示到小数点后两位:。 Any suggestions on where I can get the
toFixed(2)
to go:关于我可以在哪里获得
toFixed(2)
任何建议:
$(document).ready(function()
{
$(".sum").val("0");
$(".sum1").val("0");
$(".key").val("");
function calc() {`
var $num1 = ($.trim($(".num1").val()) != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
console.log($num1);
var $num2 = ($.trim($(".num2").val()) != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
console.log($num2);
$(".sum").val($num1 * 1.05);
$(".sum1").val($num1 * 1.05-$num1);
}
$(".key").keyup(function() {
calc();
});
});
Code for form data here.此处为表单数据的代码。
<form>
<table>
<tr>
<td><input type="text" placeholder="Ticket Price" class="num1 key"></td>
</tr>
<tr>
<td> Inc Service Fee:</td><td><input type="text" class="sum" readonly="readonly">
</td>
</tr>
<tr>
<td><input type="text" class="sum1" readonly="readonly"></td>
</tr>
</form>
Attempting to use toFixed(2) but cant get it to work for the sum and sum1 values.尝试使用 toFixed(2) 但无法使其适用于 sum 和 sum1 值。
Thank you for the help.感谢您的帮助。
You can add toFixed
inside calc
method like:您可以在
calc
方法中添加toFixed
例如:
function calc() {
var $num1 = ($.trim($(".num1").val()) != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
console.log($num1);
var $num2 = ($.trim($(".num2").val()) != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
console.log($num2);
var sum = parseFloat($num1 * 1.05).toFixed(2)
var sum1 = parseFloat($num1 * 1.05 - $num1).toFixed(2)
$(".sum").val(sum);
$(".sum1").val(sum1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.