首页 > 解决方案 > 将持续时间 (hh:mm:ss) 舍入到最接近的 0.5

问题描述

我希望将格式为 hh:mm:ss 的持续时间四舍五入到最接近的 0.5。

例如: 持续时间:2:28:55 所需输出:2.5 小时

我可以使用 MROUND: =MROUND((L3*24),0.5) 在 Excel 中轻松完成此操作,其中 L3 为 2:28:55。

我玩过一些 Math.round,但是,它似乎向下舍入。请原谅我下面的 js,效率还不是我使用 Javascript 的强项。以下四舍五入为 2。

var hms = '2:28:55';   // your input string
var a = hms.split(':'); // split it at the colons
console.log('var a = ' + a)
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hours = seconds / 60 / 60
console.log('seconds = ' + seconds);
console.log('Hours = ' + hours);
var final = Math.round(hours,0.5);
console.log(final);

提前致谢!

标签: javascript

解决方案


Math.round不带第二个参数,它总是四舍五入到最接近的整数,但你能做的只是

var final = Math.round(hours*2)/2;

var hms = '2:28:55';   // your input string
var a = hms.split(':'); // split it at the colons
console.log('var a = ' + a)
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hours = seconds / 60 / 60
console.log('seconds = ' + seconds);
console.log('Hours = ' + hours);
var final = Math.round(hours*2)/2;
console.log(final);


推荐阅读