PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/release-0.1-rc2/hive/external/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFRound.java

#
Java | 68 lines | 39 code | 8 blank | 21 comment | 9 complexity | aab81c9a47322aed616dd2adf77eb72a MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, JSON, CPL-1.0
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package org.apache.hadoop.hive.ql.udf;
  19. import java.math.BigDecimal;
  20. import java.math.RoundingMode;
  21. import org.apache.hadoop.hive.ql.exec.Description;
  22. import org.apache.hadoop.hive.ql.exec.UDF;
  23. import org.apache.hadoop.hive.serde2.io.DoubleWritable;
  24. import org.apache.hadoop.io.IntWritable;
  25. import org.apache.hadoop.io.LongWritable;
  26. /**
  27. * UDFRound.
  28. *
  29. */
  30. @Description(name = "round",
  31. value = "_FUNC_(x[, d]) - round x to d decimal places",
  32. extended = "Example:\n"
  33. + " > SELECT _FUNC_(12.3456, 1) FROM src LIMIT 1;\n" + " 12.3'")
  34. public class UDFRound extends UDF {
  35. private DoubleWritable doubleWritable = new DoubleWritable();
  36. private LongWritable longWritable = new LongWritable();
  37. public UDFRound() {
  38. }
  39. public LongWritable evaluate(DoubleWritable n) {
  40. if (n == null) {
  41. return null;
  42. }
  43. longWritable.set(BigDecimal.valueOf(n.get()).setScale(0,
  44. RoundingMode.HALF_UP).longValue());
  45. return longWritable;
  46. }
  47. public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
  48. if ((n == null) || (i == null)) {
  49. return null;
  50. }
  51. double d = n.get();
  52. if (Double.isNaN(d) || Double.isInfinite(d)) {
  53. doubleWritable.set(d);
  54. } else {
  55. doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(),
  56. RoundingMode.HALF_UP).doubleValue());
  57. }
  58. return doubleWritable;
  59. }
  60. }