Javascript returning NaN

前端 未结 1 1160
北恋
北恋 2021-01-05 01:25

I\'m attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN as the total. I believe it may

相关标签:
1条回答
  • 2021-01-05 01:51

    parseFloat and parseInt can return NaN if the first character of the string cannot be converted to a number.

    So, I would safeguard against it like this (NaN is a falsy value):

    price = parseFloat(price) || 0;
    qty = parseInt(qty, 10) || 0;
    

    Arithmetic operations on numbers with the value NaN almost always result in NaN (NaN + 5 will result in NaN.) That means, if only one of the input cannot be parsed by parseFloat or parseInt, your current code would end up calculating NaN for the subtotal.


    It's already been mentioned in the comments (by Felix mostly) but I think it's worth the emphasis as these are important concerns:

    • Always pass the radix argument to the parseInt function;
    • Do not use class for variable names: It's a reserved (not used, but reserved) keyword;
    • Don't expect the subtotal to be perfectly accurate unless you do your calculations in cents.
    0 讨论(0)
提交回复
热议问题