javascript - toFixed 返回错误的输出
问题描述
function get_tax(rent) {
var pcharges = parseFloat($('#pcharges').val());
pcharges = pcharges.toFixed(2);
rent = parseFloat(rent);
rent = rent.toFixed(2);
var tax = parseFloat((rent * 15) / 100);
tax = tax.toFixed(2);
$('#tax').val(tax);
var tot_rent = pcharges + rent + tax;
// alert(tot_rent);
$('#tot_rent').val(tot_rent);
// alert(tax);
}
function get_total(pcharges) {
pcharges = parseFloat(pcharges);
old_tot = parseFloat($('#tot_rent').val());
// alert(pcharges+old_tot);
$('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges" onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">
我想从用户那里获得租金并显示 15% 的税费,用户将手动支付电话费,然后我需要添加租金、税费、电话费。税收来得恰到好处,但总租金来得不恰当
解决方案
您正在尝试添加toFixed()
连接值的字符串值(返回字符串),使用一元加号(+)转换为浮点数,然后执行加法。
function get_tax(rent) {
var pcharges = parseFloat($('#pcharges').val());
pcharges = +pcharges.toFixed(2);
rent = parseFloat(rent);
rent = +rent.toFixed(2);
var tax = parseFloat((rent * 15) / 100);
tax = +tax.toFixed(2);
$('#tax').val(tax);
var tot_rent = pcharges + rent + tax;
// alert(tot_rent);
$('#tot_rent').val(tot_rent);
// alert(tax);
}
function get_total(pcharges) {
pcharges = parseFloat(pcharges);
old_tot = parseFloat($('#tot_rent').val());
// alert(pcharges+old_tot);
$('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges" onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">
推荐阅读
- python - 为什么在尝试导入装饰器时出现此错误?
- android - 通过在运动布局中使用 touchAnchorId 按钮不起作用
- android - 在 Android 中,Volley 中,如何传递单个字符串参数并接收字符串结果?
- excel - VBA遍历列中的值,将值放在影响公式的单元格中,并将结果公式复制并粘贴到相邻列
- php - 如何更改nova中的数据源?
- python - Dask:将自定义函数应用于 DataFrame 会出错
- css - 在 CSS 中的两种背景颜色之间叠加图像
- gatsby - GraphiQL 排序导致错误“无法读取未定义的属性 'map'”
- android - Android 相当于 iOS 的 AVMIDIPlayer?
- algorithm - 这个算法的运行时间是多少?