1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.gwe.p2elv2.functions;
18
19 import java.util.List;
20
21 import org.gwe.p2elv2.PFunction;
22 import org.gwe.p2elv2.PStatementContext;
23 import org.gwe.p2elv2.PVarValueSpace;
24
25
26
27
28
29 public class PFRange extends PFunction {
30
31 public PFRange() { super("range"); }
32
33 public PVarValueSpace calculateValues(List<String> params, PStatementContext ctx) {
34 PVarValueSpace result = new PVarValueSpace();
35 if (params.size() < 2) return result;
36
37 float start;
38 float end;
39 try {
40 start = Float.parseFloat(params.get(0));
41 end = Float.parseFloat(params.get(1));
42 } catch(NumberFormatException e) {
43 return result;
44
45 }
46
47 Float step = new Float(1);
48 String format = "x";
49 try {
50 if (params.size() == 3) {
51 format = params.get(2);
52 step = Float.valueOf(format);
53 }
54 } catch(NumberFormatException e) {
55
56 }
57
58 NumberFormatter formatter = new NumberFormatter(format);
59
60 result.add(formatter.getAsString(start));
61 for (float curr = start + step; curr <= end; curr += step) result.add(formatter.getAsString(curr));
62 return result;
63 }
64
65 class NumberFormatter {
66 private int minIntSize;
67 private int decimalPlaces = 0;
68 private int decimalPlacesConversionFactor = 0;
69
70 NumberFormatter(String format) {
71 int pointIdx = format.indexOf('.');
72 minIntSize = format.length();
73 if (pointIdx != -1) {
74 minIntSize = pointIdx;
75 decimalPlaces = format.length() - pointIdx - 1;
76 decimalPlacesConversionFactor = (int) Math.pow(10, decimalPlaces);
77 }
78 }
79
80 public String getAsString(Float number) {
81 long intPart = (long) Math.abs(number);
82 StringBuffer result = formattedInt(intPart, minIntSize);
83 if (decimalPlaces > 0) {
84 long decimals = (long)Math.round(Math.abs(number * decimalPlacesConversionFactor)) - intPart * decimalPlacesConversionFactor;
85 result.append(".").append(formattedInt(decimals, decimalPlaces));
86 }
87
88 if (number < 0) result.insert(0, "-");
89 return result.toString();
90 }
91
92 private StringBuffer formattedInt(long value, int minSize) {
93 StringBuffer result = new StringBuffer(String.valueOf(value));
94 for (int idx = minSize - result.length(); idx > 0; idx--) result.insert(0, "0");
95 return result;
96 }
97 }
98 }