01: package net.sf.saxon.functions;
02:
03: import net.sf.saxon.expr.Token;
04: import net.sf.saxon.expr.XPathContext;
05: import net.sf.saxon.om.Item;
06: import net.sf.saxon.trans.XPathException;
07: import net.sf.saxon.value.AtomicValue;
08: import net.sf.saxon.value.IntegerValue;
09: import net.sf.saxon.value.NumericValue;
10:
11: /**
12: * This class supports the ceiling(), floor(), round(), and round-to-half-even() functions,
13: * and also the abs() function
14: */
15:
16: public final class Rounding extends SystemFunction {
17:
18: public static final int FLOOR = 0;
19: public static final int CEILING = 1;
20: public static final int ROUND = 2;
21: public static final int HALF_EVEN = 3;
22: public static final int ABS = 4;
23:
24: /**
25: * Evaluate the function
26: */
27:
28: public Item evaluateItem(XPathContext context)
29: throws XPathException {
30:
31: AtomicValue val0 = (AtomicValue) argument[0]
32: .evaluateItem(context);
33: if (val0 == null)
34: return null;
35: NumericValue val = (NumericValue) val0.getPrimitiveValue();
36:
37: switch (operation) {
38: case FLOOR:
39: return val.floor();
40: case CEILING:
41: return val.ceiling();
42: case ROUND:
43: return val.round();
44: case HALF_EVEN:
45: int scale = 0;
46: if (argument.length == 2) {
47: AtomicValue scaleVal0 = (AtomicValue) argument[1]
48: .evaluateItem(context);
49: NumericValue scaleVal = (NumericValue) scaleVal0
50: .getPrimitiveValue();
51: scale = (int) scaleVal.longValue();
52: }
53: return val.roundToHalfEven(scale);
54: case ABS:
55: double sign = val.signum();
56: if (sign < 0) {
57: return val.negate();
58: } else if (sign == 0) {
59: // ensure that the result is positive zero
60: return val.arithmetic(Token.PLUS, IntegerValue.ZERO,
61: context);
62: } else {
63: return val;
64: }
65: default:
66: throw new UnsupportedOperationException(
67: "Unknown rounding function");
68: }
69: }
70:
71: }
72:
73: //
74: // The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
75: // you may not use this file except in compliance with the License. You may obtain a copy of the
76: // License at http://www.mozilla.org/MPL/
77: //
78: // Software distributed under the License is distributed on an "AS IS" basis,
79: // WITHOUT WARRANTY OF ANY KIND, either express or implied.
80: // See the License for the specific language governing rights and limitations under the License.
81: //
82: // The Original Code is: all this file.
83: //
84: // The Initial Developer of the Original Code is Michael H. Kay.
85: //
86: // Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
87: //
88: // Contributor(s): none.
89: //
|