javascriptreactjstofixed

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. I wanted to use the toFixed() function for that, but I get the error: 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...

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

I'd like to just make the number have only 2 decimal places, and rather without using 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. Thanks for help everyone! My first question on StackOverflow was resolved in 3 minutes!


Solution

  • You'll get this error if price is not a number. If it looks like a number but isn't, then it is most likely a string.

    To convert it to a number, you can use Number(), and then apply toFixed():

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