首页 > 解决方案 > 为什么 toFixed() 在我的 React 功能组件中不起作用?

问题描述

我有一个在道具中传递给功能组件的数字,在其中,我试图使它只有 2 位小数。我想为此使用该toFixed()功能,但出现错误: TypeError: props.data.price.toFixed is not a function. 我试图将这个数字从道具保存到一个局部变量中,然后调用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;

props 中发送的号码:6.22223

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

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

标签: javascriptreactjstofixed

解决方案


如果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));


推荐阅读