如何舍入变量
var x = '00:00:24.320';
var y = '00:00:19.968';
获得最终结果
x = '00:00:24';
y = '00:00:20';
答案 0 :(得分:0)
最干净的方法是使用built-in date functionality of JavaScript:
function roundToSecond(time) {
const pad = arg => `${arg}`.padStart(2, '0');
const date = new Date(`1970-01-01T${time}Z`);
date.setMilliseconds(date.getMilliseconds() + 500);
return `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;
}
console.log(roundToSecond('00:00:24.320'));
console.log(roundToSecond('00:00:19.968'));
console.log(roundToSecond('23:59:59.501'));
答案 1 :(得分:-1)
拆分,使用toFixed()
然后合并
let x = '00:00:24.320';
let [first, second, last] = x.split(':');
last = Number(last).toFixed(0);
x = `${first}:${second}:${last}`;
console.log('x: ', x);