Debian Codegraph @

net/sf/saxon/functions/FormatNumber.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.om.Item;
13 import net.sf.saxon.om.Sequence;
14 import net.sf.saxon.om.StructuredQName;
15 import net.sf.saxon.trans.DecimalFormatManager;
16 import net.sf.saxon.trans.DecimalSymbols;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.tiny.CharSlice;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.value.*;
21
22 import java.math.BigDecimal;
23 import java.math.RoundingMode;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27
28 /**
29 * Implementation of format-number() function. Note this has no dependency on number formatting in the JDK.
30 */
31
32 public class FormatNumber extends SystemFunction implements Callable {
33
34 private StructuredQName decimalFormatName; // null for the default format
35 private String picture;
36 private DecimalSymbols decimalSymbols;
37 private SubPicture[] subPictures;
38
39 /**
40 * Allow the function to create an optimized call based on the values of the actual arguments. This handles
41 * the case where the decimal format name is supplied as a literal (or defaulted), and the picture string is
42 * also supplied as a literal.
43 *
44 * @param arguments the supplied arguments to the function call
45 * @return either a function call on this function, or an expression that delivers
46 * the same result, or null indicating that no optimization has taken place
47 * @throws net.sf.saxon.trans.XPathException if an error is detected
48 */
49 @Override
50 public Expression fixArguments(Expression... arguments) throws XPathException {
51
52 if (arguments[1] instanceof Literal && (arguments.length == 2 || arguments[2] instanceof Literal)) {
53 DecimalFormatManager dfm = getRetainedStaticContext().getDecimalFormatManager();
54 assert dfm != null;
55 picture = ((Literal) arguments[1]).getValue().getStringValue();
56 if (arguments.length == 3 && !Literal.isEmptySequence(arguments[2])) {
57 try {
58 String lexicalName = ((Literal) arguments[2]).getValue().getStringValue();
59 decimalFormatName = StructuredQName.fromLexicalQName(lexicalName, false,
60 true, getRetainedStaticContext());
61 } catch (XPathException e) {
62 XPathException err = new XPathException("Invalid decimal format name. " + e.getMessage());
63 err.setErrorCode("FODF1280");
64 throw err;
65 }
66 }
67 if (decimalFormatName == null) {
68 decimalSymbols = dfm.getDefaultDecimalFormat();
69 } else {
70 decimalSymbols = dfm.getNamedDecimalFormat(decimalFormatName);
71 if (decimalSymbols == null) {
72 throw new XPathException(
73 "Decimal format " + decimalFormatName.getDisplayName() + " has not been defined", "FODF1280");
74 }
75 }
76 subPictures = getSubPictures(picture, decimalSymbols);
77 }
78 return null;
79 }
80
81 /**
82 * Analyze a picture string into two sub-pictures.
83 *
84 * @param picture the picture as written (possibly two subpictures separated by a semicolon)
85 * @param dfs the decimal format symbols
86 * @return an array of two sub-pictures, the positive and the negative sub-pictures respectively.
87 * If there is only one sub-picture, the second one is null.
88 * @throws XPathException if the picture is invalid
89 */
90
91 private static SubPicture[] getSubPictures(String picture, DecimalSymbols dfs) throws XPathException {
92 int[] picture4 = StringValue.expand(picture);
93 SubPicture[] pics = new SubPicture[2];
94 if (picture4.length == 0) {
95 XPathException err = new XPathException("format-number() picture is zero-length");
96 err.setErrorCode("FODF1310");
97 throw err;
98 }
99 int sep = -1;
100 for (int c = 0; c < picture4.length; c++) {
101 if (picture4[c] == dfs.getPatternSeparator()) {
102 if (c == 0) {
103 grumble("first subpicture is zero-length");
104 } else if (sep >= 0) {
105 grumble("more than one pattern separator");
106 } else if (sep == picture4.length - 1) {
107 grumble("second subpicture is zero-length");
108 }
109 sep = c;
110 }
111 }
112
113 if (sep < 0) {
114 pics[0] = new SubPicture(picture4, dfs);
115 pics[1] = null;
116 } else {
117 int[] pic0 = new int[sep];
118 System.arraycopy(picture4, 0, pic0, 0, sep);
119 int[] pic1 = new int[picture4.length - sep - 1];
120 System.arraycopy(picture4, sep + 1, pic1, 0, picture4.length - sep - 1);
121 pics[0] = new SubPicture(pic0, dfs);
122 pics[1] = new SubPicture(pic1, dfs);
123 }
124 return pics;
125 }
126
127 /**
128 * Format a number, given the two subpictures and the decimal format symbols
129 *
130 * @param number the number to be formatted
131 * @param subPictures the negative and positive subPictures
132 * @param dfs the decimal format symbols to be used
133 * @return the formatted number
134 */
135
136 private static CharSequence formatNumber(NumericValue number,
137 SubPicture[] subPictures,
138 DecimalSymbols dfs) {
139
140 NumericValue absN = number;
141 SubPicture pic;
142 String minusSign = "";
143 int signum = number.signum();
144 if (signum == 0 && number.isNegativeZero()) {
145 signum = -1;
146 }
147 if (signum < 0) {
148 absN = number.negate();
149 if (subPictures[1] == null) {
150 pic = subPictures[0];
151 minusSign = "" + unicodeChar(dfs.getMinusSign());
152 } else {
153 pic = subPictures[1];
154 }
155 } else {
156 pic = subPictures[0];
157 }
158
159 return pic.format(absN, dfs, minusSign);
160 }
161
162 private static void grumble(String s) throws XPathException {
163 throw new XPathException("format-number picture: " + s, "FODF1310");
164 }
165
166 /**
167 * Convert a double to a BigDecimal. In general there will be several BigDecimal values that
168 * are equal to the supplied value, and the one we want to choose is the one with fewest non-zero
169 * digits. The algorithm used is rather pragmatic: look for a string of zeroes or nines, try rounding
170 * the number down or up as appropriate, then convert the adjusted value to a double to see if it's
171 * equal to the original: if not, use the original value unchanged.
172 *
173 * @param value the double to be converted
174 * @param precision 2 for a double, 1 for a float
175 * @return the result of conversion to a double
176 */
177
178 public static BigDecimal adjustToDecimal(double value, int precision) {
179 final String zeros = precision == 1 ? "00000" : "000000000";
180 final String nines = precision == 1 ? "99999" : "999999999";
181 BigDecimal initial = BigDecimal.valueOf(value);
182 BigDecimal trial = null;
183 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C16);
184 BigDecimalValue.decimalToString(initial, fsb);
185 String s = fsb.toString();
186 int start = s.charAt(0) == '-' ? 1 : 0;
187 int p = s.indexOf(".");
188 int i = s.lastIndexOf(zeros);
189 if (i > 0) {
190 if (p < 0 || i < p) {
191 // we're in the integer part
192 // try replacing all following digits with zeros and seeing if we get the same double back
193 FastStringBuffer sb = new FastStringBuffer(s.length());
194 sb.append(s.substring(0, i));
195 for (int n = i; n < s.length(); n++) {
196 sb.append(s.charAt(n) == '.' ? '.' : '0');
197 }
198 trial = new BigDecimal(sb.toString());
199 } else {
200 // we're in the fractional part
201 // try truncating the number before the zeros and seeing if we get the same double back
202 trial = new BigDecimal(s.substring(0, i));
203
204 }
205 } else {
206 i = s.indexOf(nines);
207 if (i >= 0) {
208 if (i == start) {
209 // number starts with 99999... or -99999. Try rounding up to 100000.. or -100000...
210 FastStringBuffer sb = new FastStringBuffer(s.length() + 1);
211 if (start == 1) {
212 sb.append('-');
213 }
214 sb.append('1');
215 for (int n = start; n < s.length(); n++) {
216 sb.append(s.charAt(n) == '.' ? '.' : '0');
217 }
218 trial = new BigDecimal(sb.toString());
219 } else {
220 // try rounding up
221 while (i >= 0 && (s.charAt(i) == '9' || s.charAt(i) == '.')) {
222 i--;
223 }
224 if (i < 0 || s.charAt(i) == '-') {
225 return initial; // can't happen: we've already handled numbers starting 99999..
226 } else if (p < 0 || i < p) {
227 // we're in the integer part
228 FastStringBuffer sb = new FastStringBuffer(s.length());
229 sb.append(s.substring(0, i));
230 sb.append((char) ((int) s.charAt(i) + 1));
231 for (int n = i; n < s.length(); n++) {
232 sb.append(s.charAt(n) == '.' ? '.' : '0');
233 }
234 trial = new BigDecimal(sb.toString());
235 } else {
236 // we're in the fractional part - can ignore following digits
237 String s2 = s.substring(0, i) + (char) ((int) s.charAt(i) + 1);
238 trial = new BigDecimal(s2);
239 }
240 }
241 }
242 }
243 if (trial != null && (precision == 1 ? trial.floatValue() == value : trial.doubleValue() == value)) {
244 return trial;
245 } else {
246 return initial;
247 }
248 }
249
250
251 /**
252 * Inner class to represent one sub-picture (the negative or positive subpicture)
253 */
254
255 private static class SubPicture {
256
257 int minWholePartSize = 0;
258 int maxWholePartSize = 0;
259 int minFractionPartSize = 0;
260 int maxFractionPartSize = 0;
261 int minExponentSize = 0;
262 int scalingFactor = 0;
263 boolean isPercent = false;
264 boolean isPerMille = false;
265 String prefix = "";
266 String suffix = "";
267 int[] wholePartGroupingPositions = null;
268 int[] fractionalPartGroupingPositions = null;
269 boolean regular;
270 boolean is31 = false;
271
272 public SubPicture(int[] pic, DecimalSymbols dfs) throws XPathException {
273
274 is31 = true;
275
276 final int percentSign = dfs.getPercent();
277 final int perMilleSign = dfs.getPerMille();
278 final int decimalSeparator = dfs.getDecimalSeparator();
279 final int groupingSeparator = dfs.getGroupingSeparator();
280 final int digitSign = dfs.getDigit();
281 final int zeroDigit = dfs.getZeroDigit();
282 final int exponentSeparator = dfs.getExponentSeparator();
283
284 List<Integer> wholePartPositions = null;
285 List<Integer> fractionalPartPositions = null;
286
287 boolean foundDigit = false;
288 boolean foundDecimalSeparator = false;
289 boolean foundExponentSeparator = false;
290 boolean foundExponentSeparator2 = false;
291 for (int ch : pic) {
292 if (ch == digitSign || ch == zeroDigit || isInDigitFamily(ch, zeroDigit)) {
293 foundDigit = true;
294 break;
295 }
296 }
297 if (!foundDigit) {
298 grumble("subpicture contains no digit or zero-digit sign");
299 }
300
301 int phase = 0;
302
303 // phase = 0: passive characters at start
304 // phase = 1: digit signs in whole part
305 // phase = 2: zero-digit signs in whole part
306 // phase = 3: zero-digit signs in fractional part
307 // phase = 4: digit signs in fractional part
308 // phase = 5: zero-digit signs in exponent part
309 // phase = 6: passive characters at end
310
311 for (int c : pic) {
312 if (c == percentSign || c == perMilleSign) {
313 if (isPercent || isPerMille) {
314 grumble("Cannot have more than one percent or per-mille character in a sub-picture");
315 }
316 isPercent = c == percentSign;
317 isPerMille = c == perMilleSign;
318 switch (phase) {
319 case 0:
320 prefix += unicodeChar(c);
321 break;
322 case 1:
323 case 2:
324 case 3:
325 case 4:
326 case 5:
327 if (foundExponentSeparator) {
328 grumble("Cannot have exponent-separator as well as percent or per-mille character in a sub-picture");
329 }
330 case 6:
331 phase = 6;
332 suffix += unicodeChar(c);
333 break;
334 }
335 } else if (c == digitSign) {
336 switch (phase) {
337 case 0:
338 case 1:
339 phase = 1;
340 maxWholePartSize++;
341 break;
342 case 2:
343 grumble("Digit sign must not appear after a zero-digit sign in the integer part of a sub-picture");
344 break;
345 case 3:
346 case 4:
347 phase = 4;
348 maxFractionPartSize++;
349 break;
350 case 5:
351 grumble("Digit sign must not appear in the exponent part of a sub-picture");
352 break;
353 case 6:
354 if (foundExponentSeparator2) {
355 grumble("There must only be one exponent separator in a sub-picture");
356 } else {
357 grumble("Passive character must not appear between active characters in a sub-picture");
358 }
359 break;
360 }
361 } else if (c == zeroDigit || isInDigitFamily(c, zeroDigit)) {
362 switch (phase) {
363 case 0:
364 case 1:
365 case 2:
366 phase = 2;
367 minWholePartSize++;
368 maxWholePartSize++;
369 break;
370 case 3:
371 minFractionPartSize++;
372 maxFractionPartSize++;
373 break;
374 case 4:
375 grumble("Zero digit sign must not appear after a digit sign in the fractional part of a sub-picture");
376 break;
377 case 5:
378 minExponentSize++;
379 break;
380 case 6:
381 if (foundExponentSeparator2) {
382 grumble("There must only be one exponent separator in a sub-picture");
383 } else {
384 grumble("Passive character must not appear between active characters in a sub-picture");
385 }
386 break;
387 }
388 } else if (c == decimalSeparator) {
389 if (foundDecimalSeparator) {
390 grumble("There must only be one decimal separator in a sub-picture");
391 }
392 switch (phase) {
393 case 0:
394 case 1:
395 case 2:
396 phase = 3;
397 foundDecimalSeparator = true;
398 break;
399 case 3:
400 case 4:
401 case 5:
402 if (foundExponentSeparator) {
403 grumble("Decimal separator must not appear in the exponent part of a sub-picture");
404 }
405 break;
406 case 6:
407 grumble("Decimal separator cannot come after a character in the suffix");
408 break;
409 }
410 } else if (c == groupingSeparator) {
411 switch (phase) {
412 case 0:
413 case 1:
414 case 2:
415 if (wholePartPositions == null) {
416 wholePartPositions = new ArrayList<>(3);
417 }
418 if (wholePartPositions.contains(maxWholePartSize)) {
419 grumble("Sub-picture cannot contain adjacent grouping separators");
420 }
421 wholePartPositions.add(maxWholePartSize);
422 // note these are positions from a false offset, they will be corrected later
423 break;
424 case 3:
425 case 4:
426 if (maxFractionPartSize == 0) {
427 grumble("Grouping separator cannot be adjacent to decimal separator");
428 }
429 if (fractionalPartPositions == null) {
430 fractionalPartPositions = new ArrayList<Integer>(3);
431 }
432 if (fractionalPartPositions.contains(maxFractionPartSize)) {
433 grumble("Sub-picture cannot contain adjacent grouping separators");
434 }
435 fractionalPartPositions.add(maxFractionPartSize);
436 break;
437 case 5:
438 if (foundExponentSeparator) {
439 grumble("Grouping separator must not appear in the exponent part of a sub-picture");
440 }
441 break;
442 case 6:
443 grumble("Grouping separator found in suffix of sub-picture");
444 break;
445 }
446 } else if (c == exponentSeparator) {
447 switch (phase) {
448 case 0:
449 prefix += unicodeChar(c);
450 break;
451 case 1:
452 case 2:
453 case 3:
454 case 4:
455 phase = 5;
456 foundExponentSeparator = true;
457 break;
458 case 5:
459 if (foundExponentSeparator) {
460 foundExponentSeparator2 = true;
461 phase = 6;
462 suffix += unicodeChar(exponentSeparator);
463 }
464 break;
465 case 6:
466 suffix += unicodeChar(c);
467 break;
468 }
469 } else { // passive character found
470 switch (phase) {
471 case 0:
472 prefix += unicodeChar(c);
473 break;
474 case 1:
475 case 2:
476 case 3:
477 case 4:
478 case 5:
479 if (minExponentSize == 0 && foundExponentSeparator) {
480 phase = 6;
481 suffix += unicodeChar(exponentSeparator);
482 suffix += unicodeChar(c);
483 break;
484 }
485 case 6:
486 phase = 6;
487 suffix += unicodeChar(c);
488 break;
489 }
490 }
491 }
492
493 /* 4.7.4 Rule 3 */
494 scalingFactor = minWholePartSize;
495
496 if (maxWholePartSize == 0 && maxFractionPartSize == 0) {
497 grumble("Mantissa contains no digit or zero-digit sign");
498 }
499
500 /* 4.7.4 Rule 8 */
501 if (minWholePartSize == 0 && maxFractionPartSize == 0) { //minWholePartSize == 0 && !foundDecimalSeparator
502 if (minExponentSize != 0) {
503 minFractionPartSize = 1;
504 maxFractionPartSize = 1;
505 } else {
506 minWholePartSize = 1;
507 }
508 }
509 /* 4.7.4 Rule 9 */
510 if (minExponentSize != 0 && minWholePartSize == 0 && maxWholePartSize != 0) {
511 minWholePartSize = 1;
512 }
513 /* 4.7.4 Rule 10 */
514 if (minWholePartSize == 0 && minFractionPartSize == 0) {
515 minFractionPartSize = 1;
516 }
517
518 // System.err.println("minWholePartSize = " + minWholePartSize);
519 // System.err.println("maxWholePartSize = " + maxWholePartSize);
520 // System.err.println("minFractionPartSize = " + minFractionPartSize);
521 // System.err.println("maxFractionPartSize = " + maxFractionPartSize);
522
523 // Sort out the grouping positions
524
525 if (wholePartPositions != null) {
526 // convert to positions relative to the decimal separator
527 int n = wholePartPositions.size();
528 wholePartGroupingPositions = new int[n];
529 for (int i = 0; i < n; i++) {
530 wholePartGroupingPositions[i] =
531 maxWholePartSize - wholePartPositions.get(n - i - 1);
532 }
533 if (n == 1) {
534 regular = wholePartGroupingPositions[0] * 2 >= maxWholePartSize;
535 } else if (n > 1) {
536 regular = true;
537 int first = wholePartGroupingPositions[0];
538 for (int i = 1; i < n; i++) {
539 if (wholePartGroupingPositions[i] != (i + 1) * first) {
540 regular = false;
541 break;
542 }
543 }
544 if (regular && (maxWholePartSize - wholePartGroupingPositions[n - 1] > first)) {
545 regular = false;
546 }
547 if (regular) {
548 wholePartGroupingPositions = new int[1];
549 wholePartGroupingPositions[0] = first;
550 }
551 }
552 if (wholePartGroupingPositions[0] == 0) {
553 //grumble("Cannot have a grouping separator adjacent to the decimal separator");
554 grumble("Cannot have a grouping separator at the end of the integer part");
555 }
556 }
557
558 if (fractionalPartPositions != null) {
559 int n = fractionalPartPositions.size();
560 fractionalPartGroupingPositions = new int[n];
561 for (int i = 0; i < n; i++) {
562 fractionalPartGroupingPositions[i] = fractionalPartPositions.get(i);
563 }
564 }
565 }
566
567 /**
568 * Format a number using this sub-picture
569 *
570 * @param value the absolute value of the number to be formatted
571 * @param dfs the decimal format symbols to be used
572 * @param minusSign the representation of a minus sign to be used
573 * @return the formatted number
574 */
575
576 public CharSequence format(NumericValue value, DecimalSymbols dfs, String minusSign) {
577
578 // System.err.println("Formatting " + value);
579
580 if (value.isNaN()) {
581 return dfs.getNaN(); // changed by W3C Bugzilla 2712
582 }
583
584 int multiplier = 1;
585 if (isPercent) {
586 multiplier = 100;
587 } else if (isPerMille) {
588 multiplier = 1000;
589 }
590
591 if (multiplier != 1) {
592 try {
593 value = (NumericValue) ArithmeticExpression.compute(
594 value, Calculator.TIMES, new Int64Value(multiplier), null);
595 } catch (XPathException e) {
596 value = new DoubleValue(Double.POSITIVE_INFINITY);
597 }
598 }
599
600 if ((value instanceof DoubleValue || value instanceof FloatValue) &&
601 Double.isInfinite(value.getDoubleValue())) {
602 return minusSign + prefix + dfs.getInfinity() + suffix;
603 }
604
605
606 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C16);
607 if (value instanceof DoubleValue || value instanceof FloatValue) {
608 BigDecimal dec = adjustToDecimal(value.getDoubleValue(), 2);
609 formatDecimal(dec, sb);
610
611
612 } else if (value instanceof IntegerValue) {
613 if (minExponentSize != 0) {
614 formatDecimal(((IntegerValue) value).getDecimalValue(), sb);
615 } else {
616 formatInteger(value, sb);
617 }
618
619 } else if (value instanceof BigDecimalValue) {
620 //noinspection RedundantCast
621 formatDecimal(((BigDecimalValue) value).getDecimalValue(), sb);
622 }
623
624 // System.err.println("Justified number: " + sb.toString());
625
626 // Map the digits and decimal point to use the selected characters
627
628 int[] ib = StringValue.expand(sb);
629 int ibused = ib.length;
630 int point = sb.indexOf('.');
631 if (point == -1) {
632 point = sb.length();
633 } else {
634 ib[point] = dfs.getDecimalSeparator();
635
636 // If there is no fractional part, delete the decimal point
637 if (maxFractionPartSize == 0) {
638 ibused--;
639 }
640 }
641
642 // Map the digits
643
644 if (dfs.getZeroDigit() != '0') {
645 int newZero = dfs.getZeroDigit();
646 for (int i = 0; i < ibused; i++) {
647 int c = ib[i];
648 if (c >= '0' && c <= '9') {
649 ib[i] = c - '0' + newZero;
650 }
651 }
652 }
653
654 // Map the exponent-separator
655
656 if (dfs.getExponentSeparator() != 'e') {
657 int expS = sb.indexOf('e');
658 if (expS != -1) {
659 ib[expS] = dfs.getExponentSeparator();
660 }
661 }
662
663 // Add the whole-part grouping separators
664
665 if (wholePartGroupingPositions != null) {
666 if (regular) {
667 // grouping separators are at regular positions
668 int g = wholePartGroupingPositions[0];
669 int p = point - g;
670 while (p > 0) {
671 ib = insert(ib, ibused++, dfs.getGroupingSeparator(), p);
672 //sb.insert(p, unicodeChar(dfs.groupingSeparator));
673 p -= g;
674 }
675 } else {
676 // grouping separators are at irregular positions
677 for (int wholePartGroupingPosition : wholePartGroupingPositions) {
678 int p = point - wholePartGroupingPosition;
679 if (p > 0) {
680 ib = insert(ib, ibused++, dfs.getGroupingSeparator(), p);
681 //sb.insert(p, unicodeChar(dfs.groupingSeparator));
682 }
683 }
684 }
685 }
686
687 // Add the fractional-part grouping separators
688
689 if (fractionalPartGroupingPositions != null) {
690 // grouping separators are at irregular positions.
691 for (int i = 0; i < fractionalPartGroupingPositions.length; i++) {
692 int p = point + 1 + fractionalPartGroupingPositions[i] + i;
693 if (p < ibused) {
694 ib = insert(ib, ibused++, dfs.getGroupingSeparator(), p);
695 //sb.insert(p, dfs.groupingSeparator);
696 } else {
697 break;
698 }
699 }
700 }
701
702 // System.err.println("Grouped number: " + sb.toString());
703
704 //sb.insert(0, prefix);
705 //sb.insert(0, minusSign);
706 //sb.append(suffix);
707 FastStringBuffer res = new FastStringBuffer(prefix.length() + minusSign.length() + suffix.length() + ibused);
708 res.append(minusSign);
709 res.append(prefix);
710 for (int i = 0; i < ibused; i++) {
711 res.appendWideChar(ib[i]);
712 }
713 res.append(suffix);
714 return res;
715 }
716
717
718 /**
719 * Format a number supplied as a decimal
720 *
721 * @param dval the decimal value
722 * @param fsb the FastStringBuffer to contain the result
723 */
724 private void formatDecimal(BigDecimal dval, FastStringBuffer fsb) {
725 int exponent = 0;
726 /*if (maxFractionPartSize == 0 && minWholePartSize == 0) {
727 minWholePartSize = 1;
728 }*/ // this bit of logic is now included in the SubPicture class
729 if (minExponentSize == 0) {
730 dval = dval.setScale(maxFractionPartSize, RoundingMode.HALF_EVEN);
731 } else {
732 exponent = dval.precision() - dval.scale() - scalingFactor;
733 dval = dval.movePointLeft(exponent);
734 dval = dval.setScale(maxFractionPartSize, RoundingMode.HALF_EVEN);
735 }
736 BigDecimalValue.decimalToString(dval, fsb);
737
738 int point = fsb.indexOf('.');
739 int intDigits;
740 if (point >= 0) {
741 int zz = maxFractionPartSize - minFractionPartSize;
742 while (zz > 0) {
743 if (fsb.charAt(fsb.length() - 1) == '0') {
744 fsb.setLength(fsb.length() - 1);
745 zz--;
746 } else {
747 break;
748 }
749 }
750 intDigits = point;
751 if (fsb.charAt(fsb.length() - 1) == '.') {
752 fsb.setLength(fsb.length() - 1);
753 }
754 } else {
755 intDigits = fsb.length();
756 if (minFractionPartSize > 0) {
757 fsb.append('.');
758 for (int i = 0; i < minFractionPartSize; i++) {
759 fsb.append('0');
760 }
761 }
762 }
763 if (minWholePartSize == 0 && intDigits == 1 && fsb.charAt(0) == '0') {
764 fsb.removeCharAt(0);
765 } else {
766 fsb.prependRepeated('0', minWholePartSize - intDigits);
767 }
768 if (minExponentSize != 0) {
769 fsb.append('e');
770 IntegerValue exp = (IntegerValue) IntegerValue.makeIntegerValue(exponent);
771 String expStr = exp.toString();
772 char first = expStr.charAt(0);
773 if (first == '-') {
774 fsb.append('-');
775 expStr = expStr.substring(1);
776 }
777 int length = expStr.length();
778 if (length < minExponentSize) {
779 int zz = minExponentSize - length;
780 for (int i = 0; i < zz; i++) {
781 fsb.append('0');
782 }
783 }
784 fsb.append(expStr);
785 }
786 }
787
788 /**
789 * Format a number supplied as a integer
790 *
791 * @param value the integer value
792 * @param fsb the FastStringBuffer to contain the result
793 */
794
795 private void formatInteger(NumericValue value, FastStringBuffer fsb) {
796 if (!(minWholePartSize == 0 && value.compareTo(0) == 0)) {
797 fsb.append(value.getStringValueCS());
798 int leadingZeroes = minWholePartSize - fsb.length();
799 fsb.prependRepeated('0', leadingZeroes);
800 }
801 if (minFractionPartSize != 0) {
802 fsb.append('.');
803 for (int i = 0; i < minFractionPartSize; i++) {
804 fsb.append('0');
805 }
806 }
807 }
808
809
810 }
811
812 /**
813 * Convert a Unicode character (possibly >65536) to a String, using a surrogate pair if necessary
814 *
815 * @param ch the Unicode codepoint value
816 * @return a string representing the Unicode codepoint, either a string of one character or a surrogate pair
817 */
818
819 private static CharSequence unicodeChar(int ch) {
820 if (ch < 65536) {
821 return "" + (char) ch;
822 } else { // output a surrogate pair
823 //To compute the numeric value of the character corresponding to a surrogate
824 //pair, use this formula (all numbers are hex):
825 //(FirstChar - D800) * 400 + (SecondChar - DC00) + 10000
826 ch -= 65536;
827 char[] sb = new char[2];
828 sb[0] = (char) ((ch / 1024) + 55296);
829 sb[1] = (char) ((ch % 1024) + 56320);
830 return new CharSlice(sb, 0, 2);
831 }
832 }
833
834 /**
835 * Insert an integer into an array of integers. This may or may not modify the supplied array.
836 *
837 * @param array the initial array
838 * @param used the number of items in the initial array that are used
839 * @param value the integer to be inserted
840 * @param position the position of the new integer in the final array
841 * @return the new array, with the new integer inserted
842 */
843
844 private static int[] insert(int[] array, int used, int value, int position) {
845 if (used + 1 > array.length) {
846 array = Arrays.copyOf(array, used + 10);
847 }
848 System.arraycopy(array, position, array, position + 1, used - position);
849 array[position] = value;
850 return array;
851 }
852
853 /**
854 * Call the format-number function, supplying two or three arguments
855 *
856 * @param context the dynamic evaluation context
857 * @param arguments the values of the arguments, supplied as Sequences.
858 * <p>Generally it is advisable, if calling iterate() to process a supplied sequence, to
859 * call it only once; if the value is required more than once, it should first be converted
860 * to a {@link net.sf.saxon.om.GroundedValue} by calling the utility methd
861 * SequenceTool.toGroundedValue().</p>
862 * <p>If the expected value is a single item, the item should be obtained by calling
863 * Sequence.head(): it cannot be assumed that the item will be passed as an instance of
864 * {@link net.sf.saxon.om.Item} or {@link net.sf.saxon.value.AtomicValue}.</p>
865 * <p>It is the caller's responsibility to perform any type conversions required
866 * to convert arguments to the type expected by the callee. An exception is where
867 * this Callable is explicitly an argument-converting wrapper around the original
868 * Callable.</p>
869 * @return the result of the function
870 * @throws XPathException if any dynamic error occurs
871 */
872
873 public StringValue call(XPathContext context, Sequence[] arguments) throws XPathException {
874 int numArgs = arguments.length;
875 DecimalFormatManager dfm = getRetainedStaticContext().getDecimalFormatManager();
876 DecimalSymbols dfs;
877
878 AtomicValue av0 = (AtomicValue) arguments[0].head();
879 if (av0 == null) {
880 av0 = DoubleValue.NaN;
881 }
882 NumericValue number = (NumericValue) av0;
883
884 if (picture != null) {
885 // Decimal format and picture known statically
886 CharSequence result = formatNumber(number, subPictures, decimalSymbols);
887 return new StringValue(result);
888
889 } else {
890
891 if (numArgs == 2) {
892 dfs = dfm.getDefaultDecimalFormat();
893 } else {
894 // the decimal-format name was given as a run-time expression
895 Item arg2 = arguments[2].head();
896 if (arg2 == null) {
897 dfs = dfm.getDefaultDecimalFormat();
898 } else {
899 String lexicalName = arg2.getStringValue();
900 dfs = getNamedDecimalFormat(dfm, lexicalName);
901 }
902 }
903 String format = arguments[1].head().getStringValue();
904 SubPicture[] pics = getSubPictures(format, dfs);
905 return new StringValue(formatNumber(number, pics, dfs));
906 }
907 }
908
909 /**
910 * Get a decimal format, given its lexical QName
911 *
912 * @param dfm the decimal format manager
913 * @param lexicalName the lexical QName (or EQName) of the decimal format
914 * @return the decimal format
915 * @throws XPathException if the lexical QName is invalid or if no decimal format is found.
916 */
917
918 protected DecimalSymbols getNamedDecimalFormat(DecimalFormatManager dfm, String lexicalName) throws XPathException {
919 DecimalSymbols dfs;
920 StructuredQName qName;
921 try {
922 qName = StructuredQName.fromLexicalQName(lexicalName, false,
923 true, getRetainedStaticContext());
924 } catch (XPathException e) {
925 XPathException err = new XPathException("Invalid decimal format name. " + e.getMessage());
926 err.setErrorCode("FODF1280");
927 throw err;
928 }
929
930 dfs = dfm.getNamedDecimalFormat(qName);
931 if (dfs == null) {
932 XPathException err = new XPathException("format-number function: decimal-format '" + lexicalName + "' is not defined");
933 err.setErrorCode("FODF1280");
934 throw err;
935 }
936 return dfs;
937 }
938
939 /**
940 * Test whether a character is in the digit family identified by a particular zero digit
941 *
942 * @param ch the character to be tested
943 * @param zeroDigit a Unicode character with digit value zero
944 * @return true if the supplied character is in this digit family
945 */
946
947 private static boolean isInDigitFamily(int ch, int zeroDigit) {
948 return ch >= zeroDigit && ch < zeroDigit + 10;
949 }
950
951 /**
952 * Format a double as required by the adaptive serialization method
953 *
954 * @param value the value to be formatted
955 * @return the formatted value
956 */
957
958 public static String formatExponential(DoubleValue value) {
959 try {
960 DecimalSymbols dfs = new DecimalSymbols(Configuration.XSLT, 31);
961 dfs.setInfinity("INF");
962 SubPicture[] pics = getSubPictures("0.0##########################e0", dfs);
963 return formatNumber(value, pics, dfs).toString();
964 } catch (XPathException e) {
965 return value.getStringValue();
966 }
967 }
968
969 }
970