猿问

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

在我的反应应用程序中,我收到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 zeros

var numericCost = toFloat(cost).toFixed(2) //type - string, so can't sort it

var 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);

            })

    }



米脂
浏览 536回答 3
3回答

守着星空守着你

您尝试解决的核心问题是按数字的某个版本(数值)进行排序,然后显示另一个(具有已定义精度的字符串)。解决方案是将这两个问题分开,这样您就不会使用相同的值来排序和显示:render() {&nbsp; let data = this.props.data.sort((a, b) => {&nbsp; &nbsp; // This is the sorting function, so we need to treat the values as a number&nbsp; &nbsp; return toFloat(a.cost) - toFloat(b.cost);&nbsp; });&nbsp; return data.map(n => {&nbsp; &nbsp; // Now we're showing the data, so treat it as a string&nbsp; &nbsp; // It's already a string fetched from the API in the format needed, so just use directly&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <TableRow key={n.id}>&nbsp; &nbsp; &nbsp; &nbsp; <TableCell>{n.cost}</TableCell>&nbsp; &nbsp; &nbsp; </TableRow>&nbsp; &nbsp; );&nbsp; });}

小怪兽爱吃肉

试试这个:var cost = '900.00'var numericCost = parseFloat(cost).toFixed(2)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答