Intl.NumberFormat 返回 NAN 值。

3

为什么这个辅助函数会返回subtotaltax的值,但是对于feesordertotal却返回NAN

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,
  };
});

};

图片显示正在计算小计和税,但费用和订单总额为NAN(非数字)


那个函数传递了什么值?如果该值为 NaNformat 将返回 "NaN" - Heretic Monkey
什么是ApplicationFee?由于subTotal显示正常,它似乎是唯一可能出现问题的地方。 - raina77ow
@raina77ow Stripe 中的 ApplicationFee。我已经添加了 OrderSummary 的其余代码。 - hotrod
如果 subTotal 显示正常(这意味着它是一个合适的值),但 fee 不正常,并且唯一参与计算后者 (subtotal * ApplicationFee * 0.01) 的动态值是 ApplicationFee,则问题在于 ApplicationFee。检查该值:可以通过记录日志或在代码中设置断点来进行检查。 - raina77ow
1个回答

2

信不信由你,但是 NaN(非数字)是一个数字

typeof NaN !== 'number' // false

...所以你的第一个检查就错过了这种情况,而 NaN(作为值)通过 Intl.NumberFormat 得到了漂亮的格式化成为 $NaN 字符串。

因此,您应该考虑检查在您的情况下如何精确计算fee。这也可能修复您的 orderTotal,因为任何涉及 NaN 的计算都会导致 NaN。

另一个选择是向您的格式化函数添加特定的 NaN 检查,以防止显示奇怪的字符,例如:

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

...但在这种情况下很难确定应该显示什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接