javascript - 将持续时间 (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);
提前致谢!
解决方案
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);
推荐阅读
- javascript - 将数据从数据库加载到语义 ui 模式
- angular - 从 Observable 获取布尔值
- java - Android项目的按钮根本不起作用
- reactjs - 根据每个 id 点击编辑 React 功能组件弹出窗口
- ios - Swift 5 - 根据键将变量设置为 plist 值
- sql - 如何使用存储过程从 t-sql 表中现有的两列计算一列的值?
- javascript - 在 IE 浏览器中填充下拉值
- svelte - sveltejs/kit 不接受“npm run start”
- c - 从函数写入时,链表状态保持不变
- django - 如何配置 Django(在 docker 上)通过 Postfix 发送邮件