Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-script: Trying to add decimal places to my variable

So I look for answer similar to mine on slackoverflow didn't find anything similar to my problem. I had an issue that the decimal places for my variable below weren't showing 2 decimal places

1) max (which now work) 2) fees (the problem im having)

so I used toFixed on one of the var Max and it works :). But the thing is for using toFixed, toFixed() specifically turns a number into a string. So once the variable max is already a string, calling ' toFixed() ' on it again is an invalid operation. Cause when I tried to use it on "fees"

 var max = (principal/2)-fees;

From the function, it wouldn't work. Even if I made a new variable like:

var Test = fees.toFixed(2)

it still wouldn't work from the explanation i explain above and using https://repl.it/languages to help me. I found about Math.round(fees) as you see below but it gets rid of the decimal and show the whole number only. (the $8 is the fees variable from the code below.)

enter image description here

Is there some way i can fix the fees variable to show 2 decimal places OR do what im doing below and make a new var = to fees and use some code I never heard of. (still learning about this) thanks

<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>
like image 825
Mauricio Cuervo Avatar asked Nov 19 '25 02:11

Mauricio Cuervo


1 Answers

You should really separate your logic from your display. .toFixed should only be used when you've finalized your math and are dealing with your strings. A secondary problem you are likely experiencing is (if I assume correctly) that because 'input.value' is a string as well, then the comparing input.value to max will give you incorrect results as well.

Try

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);
    }
};
like image 92
Leroy Stav Avatar answered Nov 21 '25 16:11

Leroy Stav