所以我在slackoverflow上寻找类似于我的答案,但没有找到与我的问题类似的东西。我有一个问题,我的变量下面的小数位数没有显示2个小数位数
1)最大(现在可以使用)
2)费用(我有的问题)
所以我以前把它固定在var Max之一上,它可以工作:)。但是事情是要使用toFixed,toFixed()专门将数字转换为字符串。因此,一旦变量max已经是一个字符串,则再次对其调用'toFixed()'是无效的操作。当我尝试在“费用”上使用它时的原因
var max = (principal/2)-fees;
从功能上来说,它是行不通的。即使我做了一个新的变量,如:
var Test = fees.toFixed(2)
从我上面解释的解释并使用https://repl.it/languages来帮助我,它仍然行不通。我在下面看到的是关于Math.round(fees)的,但它摆脱了小数,只显示整数。 (8美元是下面代码中的fee变量。)
有什么办法可以固定Fees变量以显示2个小数位,或者在下面做什么即时消息,并为它们创建一个新的var =并使用一些我从未听说过的代码。 (仍然对此有所了解)谢谢
<script>
function CollFee(input, principal, fees){
var max = ( (principal/2)-fees ).toFixed(2);
var test = Math.round(fees);
//var input = this.value;
//alert(input);
if(input.value > max){
input.value = '';
var text = 'Collection Fee is too high, the total of all collection fees can only be 50% of the Original Principal.';
text = text + ' Current fee on account is $' +test+ '. THE Maximum additional fee allowed is $' +max;
alert(text);
//document.getElementById('collfee_<?php echo $dbid; ?>').value = '';
//input.value = '';
}
};
</script>
最佳答案
您应该真正将逻辑与显示区分开。 .toFixed
仅应在完成数学运算并处理字符串时使用。您可能遇到的第二个问题是(如果我假设正确的话),因为'input.value'也是一个字符串,所以将input.value与max进行比较也会得出错误的结果。
尝试
function CollFee(input, principal, fees){
var max = ( (principal/2)-fees );
var val = parseFloat(input.value)
if(val > max){
input.value = '';
var text = 'Collection Fee is too high, the total of all collection fees can only be 50% of the Original Principal.';
text = text + ' Current fee on account is $' +fee.toFixed(2)+ '. THE Maximum additional fee allowed is $' +max.toFixed(2);
alert(text);
}
};