简体   繁体   中英

My toFixed(); isn't working

I have the following JS here...

$(function($) {
    $('#CourseMenu select').change(function() {
        var sum = 0;
        $('#CourseMenu select').each(function(idx, elm) {
            sum += parseInt(elm.value, 10);
        });

     $('#total_potential').html(Math.min(sum,72).toFixed(2));
    });
});

...but the toFixed(); isn't working properly. It's not giving me the two decimal places after the whole number.

Is there something else I should add?

I've updated it to reflect @bfavaretto suggestion... but it's only returning values of .00

I have my values set to .67, 1.33, 2.67, and so forth.

You have to apply toFixed right before printing the value, not at the start:

$('#total_potential').html(Math.min(sum,72).toFixed(2));

That's because toFixed doesn't restrict the number of decimal places on a number variable, it's just a formatting function that takes a number and returns a string with that number formatted with so many decimal places. So it's supposed to be used for output only.

I believe that when you are doing:

sum += parseInt(elm.value, 10);

It is changing the type. You should make the toFixed call at the end of the function.

EDIT

To address further questions by the OP.

@webfrogs if you are ending up with a result of .00 I would make two guesses as to things that could be going wrong in your code. (1) you are using parseInt which is then giving you a value of 0 for things like .67 (not sure if this is what you want) and (2) the variable sum might not be in the same scope, you could ensure the right variable is being used by passing the context explicitly. ie

$('#CourseMenu select').each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    }).bind(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM