In my react app, I'm receiving a cost (like 990.00) from the API as a string. I'm storing it in a material UI table with sorting function. To sort the cost, it should be in number format. I'm using toFloat() to convert it to a number but I get 900 only. If I modify it to toFloat().toFixed(2), it will be convert again into a string. If I modify it to toFloat().round(2), no output at all.
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)
How do I get that number with type - number with following decimal zeros ?
Here is the Sorting method:
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);
})
}
handleRequestSort = (event, property) => {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
};
render(){
return(
{data
.sort(getSorting(order, orderBy))
.map(n => {
return (
<TableRow
hover
tabIndex={-1}
key={n.id}
>
<TableCell className={classes.tdWidth}><div className={classes.cellWidth}>${n.totalCost}</div></TableCell>
<TableCell className={classes.tdWidth}><div className={classes.cellWidth}>{n.paymentStatus}</div></TableCell>
</TableRow>
})}
)
}
}