5

我是 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
  }

}

有没有人对实现这一点的最佳实践有建议?谢谢!

4

1 回答 1

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 )

从代码中的任何位置

于 2012-09-20T13:02:42.183 回答