为了账号安全,请及时绑定邮箱和手机立即绑定

如何在JavaScript中使用以下零将数字从字符串转换为浮点数?[重复]

如何在JavaScript中使用以下零将数字从字符串转换为浮点数?[重复]

米脂 2019-04-18 15:15:26
在我的反应应用程序中,我收到API作为字符串的成本(如990.00)。我将它存储在具有排序功能的素材UI表中。要对成本进行排序,它应采用数字格式。我正在使用toFloat()将其转换为数字,但我只获得了900。如果我将它修改为toFloat()。toFixed(2),它将再次转换为字符串。如果我将它修改为toFloat()。round(2),则根本没有输出。var cost = '900.00'var numericCost = toFloat(cost) //type - number but no decimal zerosvar numericCost = toFloat(cost).toFixed(2) //type - string, so can't sort itvar numericCost = toFloat(cost).round(2) //no output (can't see the data)如何使用带有以下十进制零的类型 - 数字来获取该数字?这是排序方法:let counter = 0;function createData(projectId, projectName, projectStatus, totalCost, paymentStatus, clientName, email, phone) {    counter += 1;    return { id: counter, projectId, projectName, projectStatus, totalCost, paymentStatus, clientName, email, phone };}function desc(a, b, orderBy) {    if (b[orderBy] < a[orderBy]) {        return -1;    }    if (b[orderBy] > a[orderBy]) {        return 1;    }    return 0;}function getSorting(order, orderBy) {    return order === 'desc' ? (a, b) => desc(a, b, orderBy) : (a, b) => -desc(a, b, orderBy);}class AllTable extends React.Component {    constructor(props) {        super(props);        this.state = {            order: 'asc',            orderBy: 'userName',            data: [],        };    }componentDidMount() {        API.get('url')            .then(({ data }) => {                this.setState({                    data: data.response.map(                        job => (                            createData(                                job.project_id,                                parseFloat(job.total),                                job.payment_status,                            )                        )                    )                })            })            .catch((err) => {                console.log("AXIOS ERROR: ", err);            })    }
查看完整描述

3 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您尝试解决的核心问题是按数字的某个版本(数值)进行排序,然后显示另一个(具有已定义精度的字符串)。解决方案是将这两个问题分开,这样您就不会使用相同的值来排序和显示:


render() {

  let data = this.props.data.sort((a, b) => {

    // This is the sorting function, so we need to treat the values as a number

    return toFloat(a.cost) - toFloat(b.cost);

  });


  return data.map(n => {

    // Now we're showing the data, so treat it as a string

    // It's already a string fetched from the API in the format needed, so just use directly

    return (

      <TableRow key={n.id}>

        <TableCell>{n.cost}</TableCell>

      </TableRow>

    );

  });

}


查看完整回答
反对 回复 2019-05-17
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

试试这个:


var cost = '900.00'

var numericCost = parseFloat(cost).toFixed(2)


查看完整回答
反对 回复 2019-05-17
  • 3 回答
  • 0 关注
  • 535 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号