Intl.NumberFormat Returning NAN values

Viewed 1522

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

1 Answers

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.

Related