微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript:尝试将小数位添加到我的变量中

所以我在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变量.)

enter image description here

有什么办法可以固定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);
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐