java.text.FieldPosition#getEndIndex ( )源码实例Demo

下面列出了java.text.FieldPosition#getEndIndex ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: fitnotifications   文件: QuantityFormatter.java
/**
 * Formats the pattern with the value and adjusts the FieldPosition.
 */
public static StringBuilder format(String compiledPattern, CharSequence value,
        StringBuilder appendTo, FieldPosition pos) {
    int[] offsets = new int[1];
    SimpleFormatterImpl.formatAndAppend(compiledPattern, appendTo, offsets, value);
    if (pos.getBeginIndex() != 0 || pos.getEndIndex() != 0) {
        if (offsets[0] >= 0) {
            pos.setBeginIndex(pos.getBeginIndex() + offsets[0]);
            pos.setEndIndex(pos.getEndIndex() + offsets[0]);
        } else {
            pos.setBeginIndex(0);
            pos.setEndIndex(0);
        }
    }
    return appendTo;
}
 
源代码2 项目: fitnotifications   文件: MeasureFormat.java
/**
 * Formats a single measure per unit. 
 * 
 * An example of such a formatted string is "3.5 meters per second."
 *
 * @param measure  the measure object. In above example, 3.5 meters.
 * @param perUnit  the per unit. In above example, it is MeasureUnit.SECOND
 * @param appendTo formatted string appended here.
 * @param pos      The field position.
 * @return appendTo.
 * @stable ICU 55
 */
public StringBuilder formatMeasurePerUnit(
        Measure measure,
        MeasureUnit perUnit,
        StringBuilder appendTo,
        FieldPosition pos) {
    MeasureUnit resolvedUnit = MeasureUnit.resolveUnitPerUnit(
            measure.getUnit(), perUnit);
    if (resolvedUnit != null) {
        Measure newMeasure = new Measure(measure.getNumber(), resolvedUnit);
        return formatMeasure(newMeasure, numberFormat, appendTo, pos);
    }
    FieldPosition fpos = new FieldPosition(
            pos.getFieldAttribute(), pos.getField());
    int offset = withPerUnitAndAppend(
            formatMeasure(measure, numberFormat, new StringBuilder(), fpos),
            perUnit,
            appendTo);
    if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
        pos.setBeginIndex(fpos.getBeginIndex() + offset);
        pos.setEndIndex(fpos.getEndIndex() + offset);
    }
    return appendTo;
}
 
源代码3 项目: j2objc   文件: QuantityFormatter.java
/**
 * Formats the pattern with the value and adjusts the FieldPosition.
 */
public static StringBuilder format(String compiledPattern, CharSequence value,
        StringBuilder appendTo, FieldPosition pos) {
    int[] offsets = new int[1];
    SimpleFormatterImpl.formatAndAppend(compiledPattern, appendTo, offsets, value);
    if (pos.getBeginIndex() != 0 || pos.getEndIndex() != 0) {
        if (offsets[0] >= 0) {
            pos.setBeginIndex(pos.getBeginIndex() + offsets[0]);
            pos.setEndIndex(pos.getEndIndex() + offsets[0]);
        } else {
            pos.setBeginIndex(0);
            pos.setEndIndex(0);
        }
    }
    return appendTo;
}
 
源代码4 项目: j2objc   文件: MeasureFormat.java
/**
 * Formats a single measure per unit. 
 * 
 * An example of such a formatted string is "3.5 meters per second."
 *
 * @param measure  the measure object. In above example, 3.5 meters.
 * @param perUnit  the per unit. In above example, it is MeasureUnit.SECOND
 * @param appendTo formatted string appended here.
 * @param pos      The field position.
 * @return appendTo.
 */
public StringBuilder formatMeasurePerUnit(
        Measure measure,
        MeasureUnit perUnit,
        StringBuilder appendTo,
        FieldPosition pos) {
    MeasureUnit resolvedUnit = MeasureUnit.resolveUnitPerUnit(
            measure.getUnit(), perUnit);
    if (resolvedUnit != null) {
        Measure newMeasure = new Measure(measure.getNumber(), resolvedUnit);
        return formatMeasure(newMeasure, numberFormat, appendTo, pos);
    }
    FieldPosition fpos = new FieldPosition(
            pos.getFieldAttribute(), pos.getField());
    int offset = withPerUnitAndAppend(
            formatMeasure(measure, numberFormat, new StringBuilder(), fpos),
            perUnit,
            appendTo);
    if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
        pos.setBeginIndex(fpos.getBeginIndex() + offset);
        pos.setEndIndex(fpos.getEndIndex() + offset);
    }
    return appendTo;
}
 
源代码5 项目: j2objc   文件: IntlTestDecimalFormatAPI.java
@Test
public void testJB6134()
{
    DecimalFormat decfmt = new DecimalFormat();
    StringBuffer buf = new StringBuffer();

    FieldPosition fposByInt = new FieldPosition(NumberFormat.INTEGER_FIELD);
    decfmt.format(123, buf, fposByInt);

    buf.setLength(0);
    FieldPosition fposByField = new FieldPosition(NumberFormat.Field.INTEGER);
    decfmt.format(123, buf, fposByField);

    if (fposByInt.getEndIndex() != fposByField.getEndIndex())
    {
        errln("ERROR: End index for integer field - fposByInt:" + fposByInt.getEndIndex() +
            " / fposByField: " + fposByField.getEndIndex());
    }
}
 
源代码6 项目: j2objc   文件: NumberRegressionTests.java
/**
 * API tests for API addition request A23. FieldPosition.getBeginIndex and
 * FieldPosition.getEndIndex.
 */
@Test
public void Test4062486()
{
    DecimalFormat fmt = new DecimalFormat("#,##0.00");
    StringBuffer formatted = new StringBuffer();
    FieldPosition field = new FieldPosition(0);
    Double num = new Double(1234.5);
    fmt.format(num, formatted, field);
    if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)
        errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
    field.setBeginIndex(7);
    field.setEndIndex(4);
    if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)
        errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
}
 
源代码7 项目: j2objc   文件: Support_Format.java
protected void t_FormatWithField(int count, Format format, Object object,
                                 String text, Format.Field field, int begin, int end) {
  StringBuffer buffer = new StringBuffer();
  FieldPosition pos = new FieldPosition(field);
  format.format(object, buffer, pos);

  // System.out.println(buffer);
  // System.out.println(pos);

  if (text == null) {
    assertEquals("Test " + count + ": incorrect formatted text", this.text, buffer.toString());
  } else {
    assertEquals(text, buffer.toString());
  }

  if (begin != pos.getBeginIndex() || end != pos.getEndIndex()) {
    assertEquals(field + " " + begin + ".." + end,
                 pos.getFieldAttribute() + " " + pos.getBeginIndex() + ".." + pos.getEndIndex());
  }
}
 
源代码8 项目: fitnotifications   文件: MeasureFormat.java
/**
 * Able to format Collection<? extends Measure>, Measure[], and Measure
 * by delegating to formatMeasures.
 * If the pos argument identifies a NumberFormat field,
 * then its indices are set to the beginning and end of the first such field
 * encountered. MeasureFormat itself does not supply any fields.
 * 
 * Calling a
 * <code>formatMeasures</code> method is preferred over calling
 * this method as they give better performance.
 * 
 * @param obj must be a Collection&lt;? extends Measure&gt;, Measure[], or Measure object.
 * @param toAppendTo Formatted string appended here.
 * @param pos Identifies a field in the formatted text.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * 
 * @stable ICU53
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    int prevLength = toAppendTo.length();
    FieldPosition fpos =
            new FieldPosition(pos.getFieldAttribute(), pos.getField());
    if (obj instanceof Collection) {
        Collection<?> coll = (Collection<?>) obj;
        Measure[] measures = new Measure[coll.size()];
        int idx = 0;
        for (Object o : coll) {
            if (!(o instanceof Measure)) {
                throw new IllegalArgumentException(obj.toString());
            }
            measures[idx++] = (Measure) o;
        }
        toAppendTo.append(formatMeasures(new StringBuilder(), fpos, measures));
    } else if (obj instanceof Measure[]) {
        toAppendTo.append(formatMeasures(new StringBuilder(), fpos, (Measure[]) obj));
    } else if (obj instanceof Measure){
        toAppendTo.append(formatMeasure((Measure) obj, numberFormat, new StringBuilder(), fpos));
    } else {
        throw new IllegalArgumentException(obj.toString());            
    }
    if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
        pos.setBeginIndex(fpos.getBeginIndex() + prevLength);
        pos.setEndIndex(fpos.getEndIndex() + prevLength);
    }
    return toAppendTo;
}
 
源代码9 项目: fitnotifications   文件: MeasureFormat.java
private StringBuilder formatMeasuresSlowTrack(
        ListFormatter listFormatter,
        StringBuilder appendTo,
        FieldPosition fieldPosition,
        Measure... measures) {
    String[] results = new String[measures.length];

    // Zero out our field position so that we can tell when we find our field.
    FieldPosition fpos = new FieldPosition(
            fieldPosition.getFieldAttribute(), fieldPosition.getField());

    int fieldPositionFoundIndex = -1;
    for (int i = 0; i < measures.length; ++i) {
        ImmutableNumberFormat nf = (i == measures.length - 1 ? numberFormat : integerFormat);
        if (fieldPositionFoundIndex == -1) {
            results[i] = formatMeasure(measures[i], nf, new StringBuilder(), fpos).toString();
            if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
                fieldPositionFoundIndex = i;    
            }
        } else {
            results[i] = formatMeasure(measures[i], nf);
        }
    }
    ListFormatter.FormattedListBuilder builder =
            listFormatter.format(Arrays.asList(results), fieldPositionFoundIndex);

    // Fix up FieldPosition indexes if our field is found.
    if (builder.getOffset() != -1) {
        fieldPosition.setBeginIndex(fpos.getBeginIndex() + builder.getOffset() + appendTo.length());
        fieldPosition.setEndIndex(fpos.getEndIndex() + builder.getOffset() + appendTo.length());
    }
    return appendTo.append(builder.toString());
}
 
源代码10 项目: fitnotifications   文件: DateIntervalFormat.java
private void adjustPosition(String combiningPattern, // has {0} and {1} in it
                            String pat0, FieldPosition pos0, // pattern and pos corresponding to {0}
                            String pat1, FieldPosition pos1, // pattern and pos corresponding to {1}
                            FieldPosition posResult) {
    int index0 = combiningPattern.indexOf("{0}");
    int index1 = combiningPattern.indexOf("{1}");
    if (index0 < 0 || index1 < 0) {
        return;
    }
    int placeholderLen = 3; // length of "{0}" or "{1}"
    if (index0 < index1) {
        if (pos0.getEndIndex() > 0) {
            posResult.setBeginIndex(pos0.getBeginIndex() + index0);
            posResult.setEndIndex(pos0.getEndIndex() + index0);
        } else if (pos1.getEndIndex() > 0) {
            // here index1 >= 3
            index1 += pat0.length() - placeholderLen; // adjust for pat0 replacing {0}
            posResult.setBeginIndex(pos1.getBeginIndex() + index1);
            posResult.setEndIndex(pos1.getEndIndex() + index1);
        }
    } else {
        if (pos1.getEndIndex() > 0) {
            posResult.setBeginIndex(pos1.getBeginIndex() + index1);
            posResult.setEndIndex(pos1.getEndIndex() + index1);
        } else if (pos0.getEndIndex() > 0) {
            // here index0 >= 3
            index0 += pat1.length() - placeholderLen; // adjust for pat1 replacing {1}
            posResult.setBeginIndex(pos0.getBeginIndex() + index0);
            posResult.setEndIndex(pos0.getEndIndex() + index0);
        }
    }
}
 
源代码11 项目: fitnotifications   文件: NFRule.java
/**
 * Searches a string for another string.  If lenient parsing is off,
 * this just calls indexOf().  If lenient parsing is on, this function
 * uses CollationElementIterator to match characters, and only
 * primary-order differences are significant in determining whether
 * there's a match.
 * @param str The string to search
 * @param key The string to search "str" for
 * @param startingAt The index into "str" where the search is to
 * begin
 * @return A two-element array of ints.  Element 0 is the position
 * of the match, or -1 if there was no match.  Element 1 is the
 * number of characters in "str" that matched (which isn't necessarily
 * the same as the length of "key")
 */
private int[] findText(String str, String key, PluralFormat pluralFormatKey, int startingAt) {
    RbnfLenientScanner scanner = formatter.getLenientScanner();
    if (pluralFormatKey != null) {
        FieldPosition position = new FieldPosition(NumberFormat.INTEGER_FIELD);
        position.setBeginIndex(startingAt);
        pluralFormatKey.parseType(str, scanner, position);
        int start = position.getBeginIndex();
        if (start >= 0) {
            int pluralRuleStart = ruleText.indexOf("$(");
            int pluralRuleSuffix = ruleText.indexOf(")$", pluralRuleStart) + 2;
            int matchLen = position.getEndIndex() - start;
            String prefix = ruleText.substring(0, pluralRuleStart);
            String suffix = ruleText.substring(pluralRuleSuffix);
            if (str.regionMatches(start - prefix.length(), prefix, 0, prefix.length())
                    && str.regionMatches(start + matchLen, suffix, 0, suffix.length()))
            {
                return new int[]{start - prefix.length(), matchLen + prefix.length() + suffix.length()};
            }
        }
        return new int[]{-1, 0};
    }

    if (scanner != null) {
        // if lenient parsing is turned ON, we've got some work
        // ahead of us
        return scanner.findText(str, key, startingAt);
    }
    // if lenient parsing is turned off, this is easy. Just call
    // String.indexOf() and we're done
    return new int[]{str.indexOf(key, startingAt), key.length()};
}
 
源代码12 项目: j2objc   文件: MeasureFormat.java
/**
 * Able to format Collection&lt;? extends Measure&gt;, Measure[], and Measure
 * by delegating to formatMeasures.
 * If the pos argument identifies a NumberFormat field,
 * then its indices are set to the beginning and end of the first such field
 * encountered. MeasureFormat itself does not supply any fields.
 * 
 * Calling a
 * <code>formatMeasures</code> method is preferred over calling
 * this method as they give better performance.
 * 
 * @param obj must be a Collection&lt;? extends Measure&gt;, Measure[], or Measure object.
 * @param toAppendTo Formatted string appended here.
 * @param pos Identifies a field in the formatted text.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    int prevLength = toAppendTo.length();
    FieldPosition fpos =
            new FieldPosition(pos.getFieldAttribute(), pos.getField());
    if (obj instanceof Collection) {
        Collection<?> coll = (Collection<?>) obj;
        Measure[] measures = new Measure[coll.size()];
        int idx = 0;
        for (Object o : coll) {
            if (!(o instanceof Measure)) {
                throw new IllegalArgumentException(obj.toString());
            }
            measures[idx++] = (Measure) o;
        }
        toAppendTo.append(formatMeasures(new StringBuilder(), fpos, measures));
    } else if (obj instanceof Measure[]) {
        toAppendTo.append(formatMeasures(new StringBuilder(), fpos, (Measure[]) obj));
    } else if (obj instanceof Measure){
        toAppendTo.append(formatMeasure((Measure) obj, numberFormat, new StringBuilder(), fpos));
    } else {
        throw new IllegalArgumentException(obj.toString());            
    }
    if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
        pos.setBeginIndex(fpos.getBeginIndex() + prevLength);
        pos.setEndIndex(fpos.getEndIndex() + prevLength);
    }
    return toAppendTo;
}
 
源代码13 项目: j2objc   文件: MeasureFormat.java
private StringBuilder formatMeasuresSlowTrack(
        ListFormatter listFormatter,
        StringBuilder appendTo,
        FieldPosition fieldPosition,
        Measure... measures) {
    String[] results = new String[measures.length];

    // Zero out our field position so that we can tell when we find our field.
    FieldPosition fpos = new FieldPosition(
            fieldPosition.getFieldAttribute(), fieldPosition.getField());

    int fieldPositionFoundIndex = -1;
    for (int i = 0; i < measures.length; ++i) {
        ImmutableNumberFormat nf = (i == measures.length - 1 ? numberFormat : integerFormat);
        if (fieldPositionFoundIndex == -1) {
            results[i] = formatMeasure(measures[i], nf, new StringBuilder(), fpos).toString();
            if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
                fieldPositionFoundIndex = i;    
            }
        } else {
            results[i] = formatMeasure(measures[i], nf);
        }
    }
    ListFormatter.FormattedListBuilder builder =
            listFormatter.format(Arrays.asList(results), fieldPositionFoundIndex);

    // Fix up FieldPosition indexes if our field is found.
    if (builder.getOffset() != -1) {
        fieldPosition.setBeginIndex(fpos.getBeginIndex() + builder.getOffset() + appendTo.length());
        fieldPosition.setEndIndex(fpos.getEndIndex() + builder.getOffset() + appendTo.length());
    }
    return appendTo.append(builder.toString());
}
 
源代码14 项目: j2objc   文件: DateIntervalFormat.java
private void adjustPosition(String combiningPattern, // has {0} and {1} in it
                            String pat0, FieldPosition pos0, // pattern and pos corresponding to {0}
                            String pat1, FieldPosition pos1, // pattern and pos corresponding to {1}
                            FieldPosition posResult) {
    int index0 = combiningPattern.indexOf("{0}");
    int index1 = combiningPattern.indexOf("{1}");
    if (index0 < 0 || index1 < 0) {
        return;
    }
    int placeholderLen = 3; // length of "{0}" or "{1}"
    if (index0 < index1) {
        if (pos0.getEndIndex() > 0) {
            posResult.setBeginIndex(pos0.getBeginIndex() + index0);
            posResult.setEndIndex(pos0.getEndIndex() + index0);
        } else if (pos1.getEndIndex() > 0) {
            // here index1 >= 3
            index1 += pat0.length() - placeholderLen; // adjust for pat0 replacing {0}
            posResult.setBeginIndex(pos1.getBeginIndex() + index1);
            posResult.setEndIndex(pos1.getEndIndex() + index1);
        }
    } else {
        if (pos1.getEndIndex() > 0) {
            posResult.setBeginIndex(pos1.getBeginIndex() + index1);
            posResult.setEndIndex(pos1.getEndIndex() + index1);
        } else if (pos0.getEndIndex() > 0) {
            // here index0 >= 3
            index0 += pat1.length() - placeholderLen; // adjust for pat1 replacing {1}
            posResult.setBeginIndex(pos0.getBeginIndex() + index0);
            posResult.setEndIndex(pos0.getEndIndex() + index0);
        }
    }
}
 
源代码15 项目: j2objc   文件: NFRule.java
/**
 * Searches a string for another string.  If lenient parsing is off,
 * this just calls indexOf().  If lenient parsing is on, this function
 * uses CollationElementIterator to match characters, and only
 * primary-order differences are significant in determining whether
 * there's a match.
 * @param str The string to search
 * @param key The string to search "str" for
 * @param startingAt The index into "str" where the search is to
 * begin
 * @return A two-element array of ints.  Element 0 is the position
 * of the match, or -1 if there was no match.  Element 1 is the
 * number of characters in "str" that matched (which isn't necessarily
 * the same as the length of "key")
 */
private int[] findText(String str, String key, PluralFormat pluralFormatKey, int startingAt) {
    RbnfLenientScanner scanner = formatter.getLenientScanner();
    if (pluralFormatKey != null) {
        FieldPosition position = new FieldPosition(NumberFormat.INTEGER_FIELD);
        position.setBeginIndex(startingAt);
        pluralFormatKey.parseType(str, scanner, position);
        int start = position.getBeginIndex();
        if (start >= 0) {
            int pluralRuleStart = ruleText.indexOf("$(");
            int pluralRuleSuffix = ruleText.indexOf(")$", pluralRuleStart) + 2;
            int matchLen = position.getEndIndex() - start;
            String prefix = ruleText.substring(0, pluralRuleStart);
            String suffix = ruleText.substring(pluralRuleSuffix);
            if (str.regionMatches(start - prefix.length(), prefix, 0, prefix.length())
                    && str.regionMatches(start + matchLen, suffix, 0, suffix.length()))
            {
                return new int[]{start - prefix.length(), matchLen + prefix.length() + suffix.length()};
            }
        }
        return new int[]{-1, 0};
    }

    if (scanner != null) {
        // if lenient parsing is turned ON, we've got some work
        // ahead of us
        return scanner.findText(str, key, startingAt);
    }
    // if lenient parsing is turned off, this is easy. Just call
    // String.indexOf() and we're done
    return new int[]{str.indexOf(key, startingAt), key.length()};
}
 
源代码16 项目: j2objc   文件: DateFormatRegressionTest.java
/**
 * @bug 4101483
 */
@Test
public void Test4101483() {
    SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US);
    FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD);
    Date d = new Date(9234567890L);
    StringBuffer buf = new StringBuffer("");
    sdf.format(d, buf, fp);
    logln(sdf.format(d, buf, fp).toString());
    logln("beginIndex = " + fp.getBeginIndex());
    logln("endIndex = " + fp.getEndIndex());
    if (fp.getBeginIndex() == fp.getEndIndex())
        errln("Fail: Empty field");
}
 
源代码17 项目: fitnotifications   文件: MeasureFormat.java
private StringBuilder formatNumeric(
        Date duration,
        DateFormat formatter,
        DateFormat.Field smallestField,
        Number smallestAmount,
        StringBuilder appendTo) {
    // Format the smallest amount ahead of time.
    String smallestAmountFormatted;

    // Format the smallest amount using this object's number format, but keep track
    // of the integer portion of this formatted amount. We have to replace just the
    // integer part with the corresponding value from formatting the date. Otherwise
    // when formatting 0 minutes 9 seconds, we may get "00:9" instead of "00:09"
    FieldPosition intFieldPosition = new FieldPosition(NumberFormat.INTEGER_FIELD);
    smallestAmountFormatted = numberFormat.format(
            smallestAmount, new StringBuffer(), intFieldPosition).toString();
    // Give up if there is no integer field.
    if (intFieldPosition.getBeginIndex() == 0 && intFieldPosition.getEndIndex() == 0) {
        throw new IllegalStateException();
    }
    // Format our duration as a date, but keep track of where the smallest field is
    // so that we can use it to replace the integer portion of the smallest value.
    FieldPosition smallestFieldPosition = new FieldPosition(smallestField);
    String draft = formatter.format(
            duration, new StringBuffer(), smallestFieldPosition).toString();

    // If we find the smallest field
    if (smallestFieldPosition.getBeginIndex() != 0
            || smallestFieldPosition.getEndIndex() != 0) {
        // add everything up to the start of the smallest field in duration.
        appendTo.append(draft, 0, smallestFieldPosition.getBeginIndex());

        // add everything in the smallest field up to the integer portion
        appendTo.append(smallestAmountFormatted, 0, intFieldPosition.getBeginIndex());

        // Add the smallest field in formatted duration in lieu of the integer portion
        // of smallest field
        appendTo.append(
                draft,
                smallestFieldPosition.getBeginIndex(),
                smallestFieldPosition.getEndIndex());

        // Add the rest of the smallest field
        appendTo.append(
                smallestAmountFormatted,
                intFieldPosition.getEndIndex(),
                smallestAmountFormatted.length());
        appendTo.append(draft, smallestFieldPosition.getEndIndex(), draft.length());
    } else {
        // As fallback, just use the formatted duration.
        appendTo.append(draft);
    }
    return appendTo;
}
 
源代码18 项目: lams   文件: CellNumberFormatter.java
private void writeScientific(double value, StringBuffer output, Set<CellNumberStringMod> mods) {

        StringBuffer result = new StringBuffer();
        FieldPosition fractionPos = new FieldPosition(DecimalFormat.FRACTION_FIELD);
        decimalFmt.format(value, result, fractionPos);
        writeInteger(result, output, integerSpecials, mods, showGroupingSeparator);
        writeFractional(result, output);

        /*
        * Exponent sign handling is complex.
        *
        * In DecimalFormat, you never put the sign in the format, and the sign only
        * comes out of the format if it is negative.
        *
        * In Excel, you always say whether to always show the sign ("e+") or only
        * show negative signs ("e-").
        *
        * Also in Excel, where you put the sign in the format is NOT where it comes
        * out in the result.  In the format, the sign goes with the "e"; in the
        * output it goes with the exponent value.  That is, if you say "#e-|#" you
        * get "1e|-5", not "1e-|5". This makes sense I suppose, but it complicates
        * things.
        *
        * Finally, everything else in this formatting code assumes that the base of
        * the result is the original format, and that starting from that situation,
        * the indexes of the original special characters can be used to place the new
        * characters.  As just described, this is not true for the exponent's sign.
        * <p>
        * So here is how we handle it:
        *
        * (1) When parsing the format, remove the sign from after the 'e' and put it
        * before the first digit of the exponent (where it will be shown).
        *
        * (2) Determine the result's sign.
        *
        * (3) If it's missing, put the sign into the output to keep the result
        * lined up with the output. (In the result, "after the 'e'" and "before the
        * first digit" are the same because the result has no extra chars to be in
        * the way.)
        *
        * (4) In the output, remove the sign if it should not be shown ("e-" was used
        * and the sign is negative) or set it to the correct value.
        */

        // (2) Determine the result's sign.
        int ePos = fractionPos.getEndIndex();
        int signPos = ePos + 1;
        char expSignRes = result.charAt(signPos);
        if (expSignRes != '-') {
            // not a sign, so it's a digit, and therefore a positive exponent
            expSignRes = '+';
            // (3) If it's missing, put the sign into the output to keep the result
            // lined up with the output.
            result.insert(signPos, '+');
        }

        // Now the result lines up like it is supposed to with the specials' indexes
        ListIterator<Special> it = exponentSpecials.listIterator(1);
        Special expSign = it.next();
        char expSignFmt = expSign.ch;

        // (4) In the output, remove the sign if it should not be shown or set it to
        // the correct value.
        if (expSignRes == '-' || expSignFmt == '+') {
            mods.add(replaceMod(expSign, true, expSign, true, expSignRes));
        } else {
            mods.add(deleteMod(expSign, true, expSign, true));
        }

        StringBuffer exponentNum = new StringBuffer(result.substring(signPos + 1));
        writeInteger(exponentNum, output, exponentDigitSpecials, mods, false);
    }
 
源代码19 项目: j2objc   文件: MeasureFormat.java
private StringBuilder formatNumeric(
        Date duration,
        DateFormat formatter,
        DateFormat.Field smallestField,
        Number smallestAmount,
        StringBuilder appendTo) {
    // Format the smallest amount ahead of time.
    String smallestAmountFormatted;

    // Format the smallest amount using this object's number format, but keep track
    // of the integer portion of this formatted amount. We have to replace just the
    // integer part with the corresponding value from formatting the date. Otherwise
    // when formatting 0 minutes 9 seconds, we may get "00:9" instead of "00:09"
    FieldPosition intFieldPosition = new FieldPosition(NumberFormat.INTEGER_FIELD);
    smallestAmountFormatted = numberFormat.format(
            smallestAmount, new StringBuffer(), intFieldPosition).toString();
    // Give up if there is no integer field.
    if (intFieldPosition.getBeginIndex() == 0 && intFieldPosition.getEndIndex() == 0) {
        throw new IllegalStateException();
    }
    // Format our duration as a date, but keep track of where the smallest field is
    // so that we can use it to replace the integer portion of the smallest value.
    FieldPosition smallestFieldPosition = new FieldPosition(smallestField);
    String draft = formatter.format(
            duration, new StringBuffer(), smallestFieldPosition).toString();

    // If we find the smallest field
    if (smallestFieldPosition.getBeginIndex() != 0
            || smallestFieldPosition.getEndIndex() != 0) {
        // add everything up to the start of the smallest field in duration.
        appendTo.append(draft, 0, smallestFieldPosition.getBeginIndex());

        // add everything in the smallest field up to the integer portion
        appendTo.append(smallestAmountFormatted, 0, intFieldPosition.getBeginIndex());

        // Add the smallest field in formatted duration in lieu of the integer portion
        // of smallest field
        appendTo.append(
                draft,
                smallestFieldPosition.getBeginIndex(),
                smallestFieldPosition.getEndIndex());

        // Add the rest of the smallest field
        appendTo.append(
                smallestAmountFormatted,
                intFieldPosition.getEndIndex(),
                smallestAmountFormatted.length());
        appendTo.append(draft, smallestFieldPosition.getEndIndex(), draft.length());
    } else {
        // As fallback, just use the formatted duration.
        appendTo.append(draft);
    }
    return appendTo;
}
 
源代码20 项目: birt   文件: DateFormatWrapperFactory.java
public String format( Date date )
{
	StringBuffer str = new StringBuffer( );
	FieldPosition pos = new FieldPosition( DateFormat.DATE_FIELD );
	DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM, locale );
	if ( tz != null )
	{
		df.setTimeZone( tz );
	}
	df.format( date, str, pos );
	int endIndex;
	if ( pos.getEndIndex( ) >= str.length( ) )
	{
		endIndex = pos.getEndIndex( );
	}
	else
	{
		endIndex = pos.getEndIndex( )
				+ ( str.charAt( pos.getEndIndex( ) ) == ',' ? 2 : 1 );
	}
	if ( endIndex >= str.length( ) ) // means date is the last one, need
										// to remove separator
	{
		endIndex = pos.getBeginIndex( );
		while ( endIndex > 0 )
		{
			char ch = str.charAt( endIndex - 1 );
			if ( ch == ' '
					|| ch == ',' || ch == '/' || ch == '-' || ch == '.' )
			{
				endIndex--;
			}
			else
			{
				break;
			}
		}
		return str.substring( 0, endIndex );
	}
	return str.substring( 0, pos.getBeginIndex( ) )
			+ str.substring( endIndex );
}