为什么 toFixed() 在我的 React 功能组件中不起作用?

问题描述

我有一个在 props 中传递给功能组件的数字,在其中,我试图使它只有 2 个小数位。我想为此使用 toFixed() 函数,但出现错误TypeError: props.data.price.toFixed is not a function。我试图将这个数字从 props 保存到一个局部变量中,然后对其调用 toFixed(),但结果是一样的...

我的功能组件主体:

import React from 'react';

import classes from './Order.module.css';

const order = (props) =>{ 
    let keyTable = [];
    for(let igKey in props.data.ingredients){
        keyTable.push(igKey,"("+props.data.ingredients[igKey].toString()+")") 
    }
    let ingredientsstring = keyTable.join(' ')
    return (
        <div className={classes.Order}>
            <p>Ingrediends: {ingredientsstring}</p>
            <p>Price: <strong>USD {props.data.price.toFixed(2)}</strong></p>
        </div>
    );
}
 
export default order;

道具中发送的数量:6.22223

我只想让数字只有 2 个小数位,而不是使用 Math.round()。有人知道怎么做吗?

编辑:当我将变量转换为数字时,问题得到解决。出现错误是因为变量的类型是字符串,并且您不能对字符串调用 toFixed()。 感谢大家的帮助!我在 StackOverflow 上的第一个问题在 3 分钟内解决了!

解决方法

如果 price 不是 number,您将收到此错误。如果它看起来像一个数字但不是一个数字,那么它很可能是一个 string

要将其转换为数字,可以使用Number(),然后应用toFixed()

var str = '6.22223';
var num = Number(str);
console.log(typeof(num));
console.log(num);
console.log(num.toFixed(2));