javascript - 为什么 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 分钟内就解决了!
解决方案
如果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));
推荐阅读
- python - Pandas 中的 sort_values() 行为与文档相反
- javascript - 无法读取未定义的属性“injectReducers”
- javascript - createSwitchNavigator - TypeError:无法将类作为函数调用
- python-3.x - 合并两个数据帧并返回 int 值的函数,如年份
- c# - 使用 Prism 将视图模型属性绑定到代码中的视图属性
- ios - 导航时隐藏自定义中间按钮 swift 4
- foxpro - FoxPro SELECT 语句降低网络性能
- arrays - MongoDB 如何更新与文档数组中的条件匹配的第一项?
- blazor - 如何从 Blazor c# 代码制作 window.history.go(-1)?
- python-3.x - “Gdk-WARNING **: gdk-frame-clock: layout 不断请求,4 次尝试后放弃”是什么意思?