我是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
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人就实施这个的最佳实践提出建议?谢谢!
如果你写一个类(比如叫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
}
}
Run Code Online (Sandbox Code Playgroud)
然后你应该可以打电话:
def perc = utils.TimeUtils.calcPercentComplete( 8, 24 )
Run Code Online (Sandbox Code Playgroud)
从代码中的任何位置
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |