简体   繁体   English

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

[英]why doesn't toFixed() work in my React functional component?

I have a number passed down in props to a functional component, and in it, I'm trying to make it so that it has only 2 decimal places.我有一个在道具中传递给功能组件的数字,在其中,我试图使它只有 2 位小数。 I wanted to use the toFixed() function for that, but I get the error: TypeError: props.data.price.toFixed is not a function .我想为此使用toFixed() function ,但出现错误: TypeError: props.data.price.toFixed is not a function I tried to save this number from the props into a local variable and then call toFixed() on it, but the result is the same...我试图将这个数字从道具保存到局部变量中,然后对其调用toFixed() ,但结果是一样的......

My functional component body:我的功能组件主体:

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;

The number sent in props: 6.22223 props 中发送的号码:6.22223

I'd like to just make the number have only 2 decimal places, and rather without using Math.round().我只想让数字只有 2 位小数,而不是使用 Math.round()。 Does anyone know how to do that?有谁知道这是怎么做到的吗?

Edit: The problem is fixed when I turned the variable into a number.编辑:当我把变量变成数字时,问题就解决了。 The error was there because the variable was of type string, and you can't call toFixed() on a string.出现错误是因为变量是字符串类型,您不能在字符串上调用 toFixed()。 Thanks for help everyone!谢谢大家的帮助! My first question on StackOverflow was resolved in 3 minutes!我在 StackOverflow 上的第一个问题在 3 分钟内就解决了!

You'll get this error if price is not a number .如果price不是number ,您将收到此错误。 If it looks like a number but isn't, then it is most likely a string .如果它看起来像一个数字但不是,那么它很可能是一个string

To convert it to a number, you can use Number() , and then apply toFixed() :要将其转换为数字,您可以使用Number() ,然后应用toFixed()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM