I am new to Grails. I would like to create a reusable function that can calculate a percentage (0 - 100%) based on any 2 input values I specify. I would like this to be reusable across domains and controllers, but I am having a hard time figuring out where to put this function.
Here is my code:
def calcPercentComplete(hoursComp, hoursReq) {
def dividedVal = hoursComp/hoursReq
def Integer result = dividedVal * 100
// results will have a min and max range of 0 - 100.
switch(result){
case{result > 100}:
result = 100
break
case {result <= 0}:
result = 0
break
default: return result
}
}
Does anyone have advice on best practices for implementing this? Thanks!
If you write a class (say called TimeUtils.groovy
) and put it in src/groovy/utils
Then add something that does this as a static method:
package utils
class TimeUtils {
static Integer calcPercentComplete(hoursComp, hoursReq) {
Integer result = ( hoursComp / hoursReq ) * 100.0
result < 0 ? 0 : result > 100 ? 100 : result
}
}
You should then be able to call:
def perc = utils.TimeUtils.calcPercentComplete( 8, 24 )
From anywhere in your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With