简体   繁体   中英

Intl.NumberFormat Returning NAN values

Why is this helper function returning a value for subtotal and tax but NAN for fees and ordertotal ?

OrderSummary.jsx

const taxRate = 0.0925;

const OrderSummary = ({ addCSS, classes, merchantId, merchantName, step, setStep }) => {
  const context = useContext(ProductContext);
  let items = Array.isArray(context.cart) ? context.cart : [];
  if (step === 4) {
    items = Array.isArray(context.order) ? context.order : [];
  }
  const subtotal = items.reduce((acc, cur) => {
    return acc + cur.total * (cur.company_id === merchantId) * 1;
  }, 0);
  let tax = subtotal * taxRate;
  tax = parseFloat(tax.toFixed(2));
  let fee = subtotal * ApplicationFee * 0.01;
  fee = parseFloat(fee.toFixed(2));
  const total = subtotal + tax + fee;
    <LineItem>
      <S2>Subtotal</S2>
      <S2>{formatCurrency(subtotal)}</S2>
    </LineItem>
    <LineItem>
      <S2>Tax</S2>
      <S2>{formatCurrency(tax)}</S2>
    </LineItem>
    <LineItem>
      <S2>Fee</S2>
      <S2>{formatCurrency(fee)}</S2>
    </LineItem>

    <Total>
      <H5>Order Total</H5>
      <H5>{formatCurrency(total)}</H5>
    </Total>

helperFunctions.jsx

    export const formatCurrency = (num) => {  
      if (typeof num !== 'number') return num
      return new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(num)
    }

addTotals = () => {
let subTotal = 0;
this.state.cart.map((item) => (subTotal += item.total));
const tempFees = subTotal * ApplicationFee * 0.01;
const fees = parseFloat(tempFees.toFixed(2));
const total = subTotal + fees;
this.setState(() => {
  return {
    cartSubTotal: subTotal,
    cartFees: fees,
    cartTotal: total,
  };
});

};

Image shows a Subtotal and Tax being calculated but NAN for Fee and Order Total

Believe it or not, but NaN (Not A Number) is a number :

typeof NaN !== 'number' // false

... so your first check just misses that case, and NaN (as value) gets nicely formatted to $NaN string by Intl.NumberFormat .

So you should consider checking how exactly fee is calculated in your case. This might fix your orderTotal , too (any calculation involving NaN results in NaN).

Another option is adding specific NaN check to your formatting function to prevent showing weird characters, like this:

if (Number.isNaN(num)) // ...

... but it's really hard to tell what should be displayed in this case.

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