PageRenderTime 21ms CodeModel.GetById 17ms app.highlight 2ms RepoModel.GetById 1ms 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
 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
19package org.apache.hadoop.hive.ql.udf;
20
21import java.math.BigDecimal;
22import java.math.RoundingMode;
23
24import org.apache.hadoop.hive.ql.exec.Description;
25import org.apache.hadoop.hive.ql.exec.UDF;
26import org.apache.hadoop.hive.serde2.io.DoubleWritable;
27import org.apache.hadoop.io.IntWritable;
28import org.apache.hadoop.io.LongWritable;
29
30/**
31 * UDFRound.
32 *
33 */
34@Description(name = "round",
35    value = "_FUNC_(x[, d]) - round x to d decimal places",
36    extended = "Example:\n"
37    + "  > SELECT _FUNC_(12.3456, 1) FROM src LIMIT 1;\n" + "  12.3'")
38public class UDFRound extends UDF {
39  private DoubleWritable doubleWritable = new DoubleWritable();
40  private LongWritable longWritable = new LongWritable();
41
42  public UDFRound() {
43  }
44
45  public LongWritable evaluate(DoubleWritable n) {
46    if (n == null) {
47      return null;
48    }
49    longWritable.set(BigDecimal.valueOf(n.get()).setScale(0,
50        RoundingMode.HALF_UP).longValue());
51    return longWritable;
52  }
53
54  public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
55    if ((n == null) || (i == null)) {
56      return null;
57    }
58    double d = n.get();
59    if (Double.isNaN(d) || Double.isInfinite(d)) {
60      doubleWritable.set(d);
61    } else {
62      doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(),
63          RoundingMode.HALF_UP).doubleValue());
64    }
65    return doubleWritable;
66  }
67
68}