我是Grails的新手。我想创建一个可重用的函数,可以根据我指定的任何2个输入值计算百分比(0 - 100%)。我希望这可以在域和控制器之间重用,但我很难确定将这个功能放在哪里。
这是我的代码:
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
}
}
有没有人就实施此方法的最佳做法提出建议? 谢谢!
答案 0 :(得分:6)
如果你写一个班级(比如叫TimeUtils.groovy
)并把它放在src/groovy/utils
然后添加以静态方法执行此操作的内容:
package utils
class TimeUtils {
static Integer calcPercentComplete(hoursComp, hoursReq) {
Integer result = ( hoursComp / hoursReq ) * 100.0
result < 0 ? 0 : result > 100 ? 100 : result
}
}
然后您应该可以致电:
def perc = utils.TimeUtils.calcPercentComplete( 8, 24 )
从代码中的任何位置