将分钟舍入为只有两位小数



我在React中进行倒计时,通过解析状态中的字符串日期,计算到该日期的剩余分钟数,并显示剩余的天数和小时数,这是我的状态:

class App extends Component {
constructor(props) {
super(props)
this.state = {
deadline: 'August 05, 2018'
}
}
render() {
return (
<div className="App">
<div className="App-title">Offer Expires: {this.state.deadline}</div>
<Clock
deadline = {this.state.deadline}
/>
</div>
)
}
}
export default App;

这是我计算天、分钟、小时的方法:

getTimeUntil(deadline) {
const time = Date.parse(deadline) - Date.parse(new Date());
const seconds = Math.floor((time / 1000) % 60);
const minutes = Math.floor(time / 1000 * 60);
const hours = Math.floor((time / (1000 * 60 * 60)) % 24);
const days = Math.floor(time / (1000 * 60 * 60 * 24));
this.setState({ days, hours, minutes, seconds });
}

问题是它以毫秒为单位以以下格式返回分钟:

天数:5小时:11分钟:28467780秒:54

我想把它们四舍五入到两位小数,比如:

天数:5小时:11分钟:28秒:54

我已尝试添加minutes.toFixed(2)minutes.toPrecision(2)但它没有绕过他们,我怎么能做到呢?

我认为这只是你的分钟计算失败了。它应该是类似的东西

const minutes = Math.floor(time / (1000 * 60) % 60);

显示前两位数字对我来说似乎是错误的。应该使用%计算分钟,就像使用小时和秒一样。

const minutes = Math.floor((time / 1000 * 60) % 60);

最新更新