Earlier we’ve seen how you can round time duration quarterly in JavaScript. In this example, you’ll learn how you can get time duration rounded in payroll in JavaScript. Here’s a table to demonstrate how the conversion is going to look like:
Time duration | Rounded payroll value |
25 minutes | 0.5 |
57 minutes | 1.0 |
1 hour 10 minutes | 1.25 |
1 hour 42 minutes | 1.75 |
Here’s the code I’ve written which’ll make the above conversion:
function getHoursAndMinsRoundedPayroll(durationInSeconds) {
function getMinutesPayroll(minutes) {
const minutesInt = parseInt(minutes)
let payrollMinsInt = 0
if (minutesInt > 0 && minutesInt <= 15) {
payrollMinsInt = 25
} else if (minutesInt >= 16 && minutesInt <= 30) {
payrollMinsInt = 50
} else if (minutesInt >= 31 && minutesInt <= 45) {
payrollMinsInt = 75
}
return payrollMinsInt
}
const durationInMinutes = durationInSeconds / 60
let hours = durationInMinutes / 60
const roundedHours = Math.floor(hours)
const minutes = (hours - roundedHours) * 60
const h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours
const m = (Math.round(minutes / 15) * 15) % 60
const mPayroll = getMinutesPayroll(m)
return `${parseInt(h.toString())}.${mPayroll.toString()}`
}
// 25 minutes = 1500 seconds
console.log(getHoursAndMinsRoundedPayroll(1500))
// 57 minutes = 3420 seconds
console.log(getHoursAndMinsRoundedPayroll(3420))
// 1 hour 10 minutes = 4200 seconds
console.log(getHoursAndMinsRoundedPayroll(4200))
// 1 hour 42 minutes = 6120 seconds
console.log(getHoursAndMinsRoundedPayroll(6120))
//output
0.50
1.0
1.25
1.75
Code language: JavaScript (javascript)
I’ve created a function named getHoursAndMinsRoundedPayroll which takes in the duration of the time period in seconds. There’s an inner function named getMinutesPayroll which rounds off the minutes quarterly from the value of 100%. For instance, 13 minutes would be converted to 15 minutes, and thereby 15/60 * 100 = 25%. The function otherwise rounds off the hours directly and returns the result of the computation as a single output.
If you have any suggestions or doubts, let me know in the comments section below!