简体   繁体   English

我的toFixed(); 没用

[英]My toFixed(); isn't working

I have the following JS here... 我在这里有以下JS ...

$(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(); ...但是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 我已经更新它以反映@bfavaretto建议...但是它只返回.00的值

I have my values set to .67, 1.33, 2.67, and so forth. 我将值设置为.67、1.33、2.67,依此类推。

You have to apply toFixed right before printing the value, not at the start: 你必须申请toFixed正确打印的价值,而不是在开始之前:

$('#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. 这是因为toFixed并不限制数字变量的小数位数,它只是一个格式化函数,该函数接受一个数字并返回一个具有该数字的字符串,该数字的位数被设置为许多小数位。 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. 您应该在函数末尾进行toFixed调用。

EDIT 编辑

To address further questions by the OP. 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. @webfrogs如果最后得到的结果是.00,那么我会对代码中可能出错的事情做出两个猜测。 (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. (1)您正在使用parseInt ,然后为.67之类的东西给您提供0值(不确定这是否是您想要的),以及(2)变量sum可能不在同一范围内,您可以确保通过显式传递上下文来使用right变量。 ie

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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