Java 类java.text.FieldPosition 实例源码

项目:fitnotifications    文件:SimpleDateFormat.java   
/**
 * Formats a single field. This is the version called internally; it
 * adds fieldNum and capitalizationContext parameters.
 *
 * @internal
 * @deprecated This API is ICU internal only.
 */
@Deprecated
protected String subFormat(char ch, int count, int beginOffset,
                           int fieldNum, DisplayContext capitalizationContext,
                           FieldPosition pos,
                           Calendar cal)
{
    StringBuffer buf = new StringBuffer();
    subFormat(buf, ch, count, beginOffset, fieldNum, capitalizationContext, pos, cal);
    return buf.toString();
}
项目:pay-xxpay-master    文件:AmountUtil.java   
/**
 * 将字符串"元"转换成"分"
 * @param str
 * @return
 */
public static String convertDollar2Cent(String str) {
    DecimalFormat df = new DecimalFormat("0.00");
    StringBuffer sb = df.format(Double.parseDouble(str),
            new StringBuffer(), new FieldPosition(0));
    int idx = sb.toString().indexOf(".");
    sb.deleteCharAt(idx);
    for (; sb.length() != 1;) {
        if(sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        } else {
            break;
        }
    }
    return sb.toString();
}
项目:GoupilBot    文件:DateTimeLib.java   
/**
 * Retourne un tableau avec les informations sur le format standard des dates et heures.<br>
 * [0] = séparateur dans une date, exemple: "."<br>
 * [1] = séparateur sous la forme d'une expression regex, exemple: "\."<br>
 * [2] = le format d'une date, exemple: "dd.MM.yy"<br>
 * [3] = séparateur d'un temps, exemple: ":"<br>
 * [4] = séparateur d'un temps sous la forme d'une expression regex, exemple: "\:"<br>
 * [5] = le format d'un temps, exemple: "HH:mm:ss"<br>
 *
 * @return un tableau avec les informations sus-mentionnées
 */
public static String[] getLocalePatternInfo() {
  String info[] = new String[6];
  DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
  FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);

  StringBuffer buffer = new StringBuffer();
  StringBuffer format = dateFormat.format(getNow(), buffer, yearPosition);
  String pattern = new SimpleDateFormat().toPattern();
  String datePattern = pattern.substring(0, format.length());
  String hourPattern = pattern.substring(format.length() + 1);

  // infos sur le format des dates
  int yearIdx = yearPosition.getBeginIndex() - 1;
  info[0] = format.substring(yearIdx, yearIdx + 1);
  info[1] = "\\" + info[0];
  info[2] = datePattern;

  // infos sur le format des heures
  info[3] = hourPattern.substring(2, 3);
  info[4] = "\\" + info[3];
  info[5] = hourPattern + info[3] + "ss";
  return info;
}
项目: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;
}
项目:fitnotifications    文件:ChineseDateFormat.java   
/**
 * {@inheritDoc}
 * @internal
 * @deprecated This API is ICU internal only.
 */
@Override
@Deprecated
protected void subFormat(StringBuffer buf,
                         char ch, int count, int beginOffset,
                         int fieldNum, DisplayContext capitalizationContext,
                         FieldPosition pos,
                         Calendar cal) {

    // Logic to handle 'G' for chinese calendar is moved into SimpleDateFormat,
    // and obsolete pattern char 'l' is now ignored in SimpleDateFormat, so we
    // just use its implementation
    super.subFormat(buf, ch, count, beginOffset, fieldNum, capitalizationContext, pos, cal);

    // The following is no longer an issue for this subclass...
    // TODO: add code to set FieldPosition for 'G' and 'l' fields. This
    // is a DESIGN FLAW -- subclasses shouldn't have to duplicate the
    // code that handles this at the end of SimpleDateFormat.subFormat.
    // The logic should be moved up into SimpleDateFormat.format.
}
项目:jaffa-framework    文件:MaxLengthValidator.java   
/** This method will ensure that the input Number does not exceed the specified limits.
 * @param input The number whose length is to be checked.
 * @param intSize The upper limit on the number of digits allowed before the decimal.
 * @param fracSize The upper limit on the number of digits allowed after the decimal.
 * @return a true if the input Number is within the specified limits.
 */
private boolean checkLength(Number input, Integer intSize, Integer fracSize) {
    if (input != null && (intSize != null || fracSize != null)) {
        double value = Math.abs(input.doubleValue());

        if (intSize != null) {
            double intLimit = Math.pow(10, intSize.intValue());
            if ((long) value >= (long) intLimit)
                return false;
        }

        if (fracSize != null) {
            // @todo: should find a much more efficient way of finding the no. of fractional digits
            StringBuffer buf = new StringBuffer();
            FieldPosition fp = new FieldPosition(NumberFormat.FRACTION_FIELD);
            NumberFormat df = NumberFormat.getNumberInstance();
            df.setGroupingUsed(false);
            df.setMaximumFractionDigits(20); // THIS SHOULD BE SUFFICIENT
            df.format(value, buf, fp);
            String fracString = buf.substring(fp.getBeginIndex(), fp.getEndIndex());
            if (fracString != null && fracString.length() > fracSize.intValue())
                return false;
        }
    }
    return true;
}
项目:fitnotifications    文件:MeasureFormat.java   
private StringBuilder formatMeasure(
        Measure measure,
        ImmutableNumberFormat nf,
        StringBuilder appendTo,
        FieldPosition fieldPosition) {
    Number n = measure.getNumber();
    MeasureUnit unit = measure.getUnit();
    if (unit instanceof Currency) {
        return appendTo.append(
                currencyFormat.format(
                        new CurrencyAmount(n, (Currency) unit),
                        new StringBuffer(),
                        fieldPosition));

    }
    StringBuffer formattedNumber = new StringBuffer();
    StandardPlural pluralForm = QuantityFormatter.selectPlural(
            n, nf.nf, rules, formattedNumber, fieldPosition);
    String formatter = getPluralFormatter(unit, formatWidth, pluralForm.ordinal());
    return QuantityFormatter.format(formatter, formattedNumber, appendTo, fieldPosition);
}
项目:fitnotifications    文件:TimeZoneFormat.java   
/**
 * {@inheritDoc}
 *
 * @stable ICU 49
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
    StringBuffer toAppendTo = new StringBuffer();
    FieldPosition pos = new FieldPosition(0);
    toAppendTo = format(obj, toAppendTo, pos);

    // supporting only DateFormat.Field.TIME_ZONE
    AttributedString as = new AttributedString(toAppendTo.toString());
    as.addAttribute(DateFormat.Field.TIME_ZONE, DateFormat.Field.TIME_ZONE);

    return as.getIterator();
}
项目:etomica    文件:ScientificFormat.java   
private StringBuffer exponentialFormat(double mantissa, double exponent, 
                   StringBuffer result, 
                   FieldPosition fieldPosition) 
   {
FieldPosition intfp = new FieldPosition(0);
FieldPosition ruse, euse;

if (fieldPosition.getField() == EXPONENT_FIELD) {
    ruse = intfp;
    euse = fieldPosition;
}
else {
    ruse = fieldPosition;
    euse = intfp;
}

dfmt.format(mantissa, result, ruse);
efmt.format(exponent, result, euse);

return result;
   }
项目:myfaces-trinidad    文件:ColorFormat.java   
@Override
public final StringBuffer format(
  Object obj, 
  StringBuffer toAppendTo,
  FieldPosition fieldPosition)
{
  if (obj instanceof Color)
  {
    return format((Color)obj, toAppendTo, fieldPosition);
  }
  else if (obj instanceof Number)
  {
    return format(new Color(((Number)obj).intValue()),
                  toAppendTo, fieldPosition);
  }
  else 
  {
    throw 
      new IllegalArgumentException(_LOG.getMessage(
        "CANNOT_FORMAT_GIVEN_OBJECT_AS_COLOR"));
  }
}
项目:traccar-service    文件:AddressFormat.java   
@Override
public StringBuffer format(Object o, StringBuffer stringBuffer, FieldPosition fieldPosition) {
    Address address = (Address) o;
    String result = format;

    result = replace(result, "%p", address.getPostcode());
    result = replace(result, "%c", address.getCountry());
    result = replace(result, "%s", address.getState());
    result = replace(result, "%d", address.getDistrict());
    result = replace(result, "%t", address.getSettlement());
    result = replace(result, "%u", address.getSuburb());
    result = replace(result, "%r", address.getStreet());
    result = replace(result, "%h", address.getHouse());

    result = result.replaceAll("^[, ]*", "");

    return stringBuffer.append(result);
}
项目:n4js    文件:SimpleTimeFormat.java   
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (obj instanceof Double) {
        return toAppendTo.append(convertWithFormat(((Double) obj).longValue(), NO_DECIMAL));
    }
    throw new RuntimeException("Unexpected call.");
}
项目:lttng-scope    文件:LamiLabelFormat.java   
@Override
public @Nullable StringBuffer format(@Nullable Object obj, @Nullable StringBuffer toAppendTo, @Nullable FieldPosition pos) {
    if (obj == null || toAppendTo == null) {
        return new StringBuffer(SWTCHART_EMPTY_LABEL);
    }

    Double doubleObj = (Double) obj;

    /*
     * Return a string buffer with a space in it since SWT does not like to
     * draw empty strings.
     */
    if ((doubleObj % 1 != 0) || !fMap.containsValue((doubleObj.intValue()))) {
        return new StringBuffer(SWTCHART_EMPTY_LABEL);
    }

    for (Entry<String, Integer> entry : fMap.entrySet()) {
        /*
         * FIXME: Find if the elements are the same, based on their double
         * value, because SWTChart uses double values so we do the same
         * check. The loss of precision could lead to false positives.
         */
        if (Double.compare(entry.getValue().doubleValue(), doubleObj.doubleValue()) == 0) {
            if (entry.getKey() == null) {
                return new StringBuffer(UNKNOWN_REPRESENTATION);
            }
            return toAppendTo.append(entry.getKey());
        }
    }
    return new StringBuffer(SWTCHART_EMPTY_LABEL);
}
项目:parabuild-ci    文件:MonthDateFormat.java   
/**
 * Formats the given date.
 * 
 * @param date  the date.
 * @param toAppendTo  the string buffer.
 * @param fieldPosition  the field position.
 * 
 * @return The formatted date.
 */
public StringBuffer format(Date date, StringBuffer toAppendTo,
                           FieldPosition fieldPosition) {
    this.calendar.setTime(date);
    int month = this.calendar.get(Calendar.MONTH);
    toAppendTo.append(this.months[month]);
    if (this.showYear[month]) {
        toAppendTo.append(this.yearFormatter.format(date));
    }
    return toAppendTo;   
}
项目:fitnotifications    文件:QuantityFormatter.java   
/**
 * Selects the standard plural form for the number/formatter/rules.
 */
public static StandardPlural selectPlural(
        Number number, NumberFormat fmt, PluralRules rules,
        StringBuffer formattedNumber, FieldPosition pos) {
    UFieldPosition fpos = new UFieldPosition(pos.getFieldAttribute(), pos.getField());
    fmt.format(number, formattedNumber, fpos);
    // TODO: Long, BigDecimal & BigInteger may not fit into doubleValue().
    FixedDecimal fd = new FixedDecimal(
            number.doubleValue(),
            fpos.getCountVisibleFractionDigits(), fpos.getFractionDigits());
    String pluralKeyword = rules.select(fd);
    pos.setBeginIndex(fpos.getBeginIndex());
    pos.setEndIndex(fpos.getEndIndex());
    return StandardPlural.orOtherFromString(pluralKeyword);
}
项目:fitnotifications    文件: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)
 * 
 * @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;
}
项目:fitnotifications    文件:MeasureFormat.java   
/**
 * Formats a sequence of measures.
 * 
 * If the fieldPosition 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.
 * 
 * @param appendTo the formatted string appended here.
 * @param fieldPosition Identifies a field in the formatted text.
 * @param measures the measures to format.
 * @return appendTo.
 * @see MeasureFormat#formatMeasures(Measure...)
 * @stable ICU 53
 */
public StringBuilder formatMeasures(
        StringBuilder appendTo, FieldPosition fieldPosition, Measure... measures) {
    // fast track for trivial cases
    if (measures.length == 0) {
        return appendTo;
    }
    if (measures.length == 1) {
        return formatMeasure(measures[0], numberFormat, appendTo, fieldPosition);
    }

    if (formatWidth == FormatWidth.NUMERIC) {
        // If we have just hour, minute, or second follow the numeric
        // track.
        Number[] hms = toHMS(measures);
        if (hms != null) {
            return formatNumeric(hms, appendTo);
        }
    }

    ListFormatter listFormatter = ListFormatter.getInstance(
            getLocale(), formatWidth.getListFormatterStyle());
    if (fieldPosition != DontCareFieldPosition.INSTANCE) {
        return formatMeasuresSlowTrack(listFormatter, appendTo, fieldPosition, measures);
    }
    // Fast track: No field position.
    String[] results = new String[measures.length];
    for (int i = 0; i < measures.length; i++) {
        results[i] = formatMeasure(
                measures[i],
                i == measures.length - 1 ? numberFormat : integerFormat);
    }
    return appendTo.append(listFormatter.format((Object[]) results));

}
项目: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());
}
项目:fitnotifications    文件:NumberFormat.java   
/**
 * Specialization of format.
 * @see java.text.Format#format(Object)
 * @stable ICU 2.0
 */
public final String format(long number) {
    StringBuffer buf = new StringBuffer(19);
    FieldPosition pos = new FieldPosition(0);
    format(number, buf, pos);
    return buf.toString();
}
项目:okwallet    文件:BtcFormat.java   
private StringBuffer format(Object qty, StringBuffer toAppendTo, FieldPosition pos,
                                        int minDecimals, List<Integer> fractionGroups) {
    checkArgument(minDecimals >= 0, "There can be no fewer than zero fractional decimal places");
    synchronized (numberFormat) {
        DecimalFormatSymbols anteSigns = numberFormat.getDecimalFormatSymbols();
        BigDecimal denominatedUnitCount = denominateAndRound(inSatoshis(qty), minDecimals, fractionGroups);
        List<Integer> antePlaces =
            setFormatterDigits(numberFormat, denominatedUnitCount.scale(), denominatedUnitCount.scale());
        StringBuffer s = numberFormat.format(denominatedUnitCount, toAppendTo, pos);
        numberFormat.setDecimalFormatSymbols(anteSigns);
        setFormatterDigits(numberFormat, antePlaces.get(0), antePlaces.get(1));
        return s;
    }
}
项目:openNaEF    文件:InetAddressFormatter.java   
public StringBuffer format(final Object obj, final StringBuffer sb,
                           final FieldPosition pos) {
    if (obj instanceof InetAddress) {
        sb.append(((InetAddress) obj).getHostAddress());
    }
    return sb;
}
项目:fitnotifications    文件:NumberFormat.java   
/**
 * {@icu} Formats a CurrencyAmount. Specialization of format.
 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
 * @stable ICU 3.0
 */
public StringBuffer format(CurrencyAmount currAmt,
                           StringBuffer toAppendTo,
                           FieldPosition pos) {
    // Default implementation -- subclasses may override
    synchronized(this) {
        Currency save = getCurrency(), curr = currAmt.getCurrency();
        boolean same = curr.equals(save);
        if (!same) setCurrency(curr);
        format(currAmt.getNumber(), toAppendTo, pos);
        if (!same) setCurrency(save);
    }
    return toAppendTo;
}
项目:fitnotifications    文件:TimeUnitFormat.java   
/**
 * @internal
 * @deprecated This API is ICU internal only.
 */
@Deprecated
@Override
public StringBuilder formatMeasures(
        StringBuilder appendTo, FieldPosition fieldPosition, Measure... measures) {
    return mf.formatMeasures(appendTo, fieldPosition, measures);
}
项目:fitnotifications    文件:RuleBasedNumberFormat.java   
/**
 * <strong style="font-family: helvetica; color: red;">NEW</strong>
 * Implement com.ibm.icu.text.NumberFormat:
 * Format a BigInteger.
 * @stable ICU 2.0
 */
@Override
public StringBuffer format(BigInteger number,
                           StringBuffer toAppendTo,
                           FieldPosition pos) {
    return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
}
项目:fitnotifications    文件:RuleBasedNumberFormat.java   
/**
 * <strong style="font-family: helvetica; color: red;">NEW</strong>
 * Implement com.ibm.icu.text.NumberFormat:
 * Format a BigDecimal.
 * @stable ICU 2.0
 */
@Override
public StringBuffer format(java.math.BigDecimal number,
                           StringBuffer toAppendTo,
                           FieldPosition pos) {
    return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
}
项目:fitnotifications    文件:RuleBasedNumberFormat.java   
/**
 * <strong style="font-family: helvetica; color: red;">NEW</strong>
 * Implement com.ibm.icu.text.NumberFormat:
 * Format a BigDecimal.
 * @stable ICU 2.0
 */
@Override
public StringBuffer format(com.ibm.icu.math.BigDecimal number,
                           StringBuffer toAppendTo,
                           FieldPosition pos) {
    if (MIN_VALUE.compareTo(number) >= 0 || MAX_VALUE.compareTo(number) <= 0) {
        // We're outside of our normal range that this framework can handle.
        // The DecimalFormat will provide more accurate results.
        return getDecimalFormat().format(number, toAppendTo, pos);
    }
    if (number.scale() == 0) {
        return format(number.longValue(), toAppendTo, pos);
    }
    return format(number.doubleValue(), toAppendTo, pos);
}
项目: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);
        }
    }
}
项目:fitnotifications    文件:DateIntervalFormat.java   
private final StringBuffer fallbackFormat(Calendar fromCalendar,
                                          Calendar toCalendar,
                                          boolean fromToOnSameDay,
                                          StringBuffer appendTo,
                                          FieldPosition pos)  {
        String fullPattern = null; // for saving the pattern in fDateFormat
        boolean formatDatePlusTimeRange = (fromToOnSameDay && fDatePattern != null && fTimePattern != null);
        // the fall back
        if (formatDatePlusTimeRange) {
            fullPattern = fDateFormat.toPattern(); // save current pattern, restore later
            fDateFormat.applyPattern(fTimePattern);
        }
        FieldPosition otherPos = new FieldPosition(pos.getField());
        StringBuffer earlierDate = new StringBuffer(64);
        earlierDate = fDateFormat.format(fromCalendar, earlierDate, pos);
        StringBuffer laterDate = new StringBuffer(64);
        laterDate = fDateFormat.format(toCalendar, laterDate, otherPos);
        String fallbackPattern = fInfo.getFallbackIntervalPattern();
        adjustPosition(fallbackPattern, earlierDate.toString(), pos, laterDate.toString(), otherPos, pos);
        String fallbackRange = SimpleFormatterImpl.formatRawPattern(
                fallbackPattern, 2, 2, earlierDate, laterDate);
        if (formatDatePlusTimeRange) {
            // fallbackRange has just the time range, need to format the date part and combine that
            fDateFormat.applyPattern(fDatePattern);
            StringBuffer datePortion = new StringBuffer(64);
            otherPos.setBeginIndex(0);
            otherPos.setEndIndex(0);
            datePortion = fDateFormat.format(fromCalendar, datePortion, otherPos);
            adjustPosition(fDateTimeFormat, fallbackRange, pos, datePortion.toString(), otherPos, pos);
            fallbackRange = SimpleFormatterImpl.formatRawPattern(
                    fDateTimeFormat, 2, 2, fallbackRange, datePortion);
        }
        appendTo.append(fallbackRange);
        if (formatDatePlusTimeRange) {
            // restore full pattern
            fDateFormat.applyPattern(fullPattern);
        }
        return appendTo;
}
项目:etomica    文件:ScientificFormat.java   
public StringBuffer format(double number, StringBuffer result, 
               FieldPosition fieldPosition) {
if (expmode) {
    return exponentialFormat(number, result, fieldPosition);
}
else if (flexmode) {
    int sign = (number < 0) ? -1 : 1;
    int mxwd = getMaxWidth();
    double mantissa = Math.abs(number),
       exponent = 0;

    if (mantissa != 0) {
    for(; mantissa > 10; mantissa /= 10, exponent++);
    for(; mantissa <  1; mantissa *= 10, exponent--);
    }

    if (exponent < (1 - dfmt.getMaximumFractionDigits()) ||
    exponent - dfmt.getMaximumFractionDigits() > mxwd - 2) 
    {
    return exponentialFormat(sign*mantissa, exponent,
                 result, fieldPosition);
    }
    StringBuffer tmp = new StringBuffer();
    dfmt.format(number, tmp, fieldPosition);
    if (tmp.length() > mxwd) {
        return exponentialFormat(sign*mantissa, exponent, 
                     result, fieldPosition);
    }
    result.append(tmp.toString());
    return result;
}
else {
    return dfmt.format(number, result, fieldPosition);
}

   }
项目:fitnotifications    文件:DecimalFormat.java   
private StringBuffer subformat(int number, StringBuffer result, FieldPosition fieldPosition,
                               boolean isNegative, boolean isInteger, boolean parseAttr) {
    if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT) {
        // compute the plural category from the digitList plus other settings
        return subformat(currencyPluralInfo.select(getFixedDecimal(number)),
                         result, fieldPosition, isNegative,
                         isInteger, parseAttr);
    } else {
        return subformat(result, fieldPosition, isNegative, isInteger, parseAttr);
    }
}
项目:fitnotifications    文件:DecimalFormat.java   
private StringBuffer subformat(double number, StringBuffer result, FieldPosition fieldPosition,
                               boolean isNegative,
        boolean isInteger, boolean parseAttr) {
    if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT) {
        // compute the plural category from the digitList plus other settings
        return subformat(currencyPluralInfo.select(getFixedDecimal(number)),
                         result, fieldPosition, isNegative,
                         isInteger, parseAttr);
    } else {
        return subformat(result, fieldPosition, isNegative, isInteger, parseAttr);
    }
}
项目:fitnotifications    文件:DecimalFormat.java   
private StringBuffer subformat(String pluralCount, StringBuffer result, FieldPosition fieldPosition,
        boolean isNegative, boolean isInteger, boolean parseAttr) {
    // There are 2 ways to activate currency plural format: by applying a pattern with
    // 3 currency sign directly, or by instantiate a decimal formatter using
    // PLURALCURRENCYSTYLE.  For both cases, the number of currency sign in the
    // pattern is 3.  Even if the number of currency sign in the pattern is 3, it does
    // not mean we need to reset the pattern.  For 1st case, we do not need to reset
    // pattern.  For 2nd case, we might need to reset pattern, if the default pattern
    // (corresponding to plural count 'other') we use is different from the pattern
    // based on 'pluralCount'.
    //
    // style is only valid when decimal formatter is constructed through
    // DecimalFormat(pattern, symbol, style)
    if (style == NumberFormat.PLURALCURRENCYSTYLE) {
        // May need to reset pattern if the style is PLURALCURRENCYSTYLE.
        String currencyPluralPattern = currencyPluralInfo.getCurrencyPluralPattern(pluralCount);
        if (formatPattern.equals(currencyPluralPattern) == false) {
            applyPatternWithoutExpandAffix(currencyPluralPattern, false);
        }
    }
    // Expand the affix to the right name according to the plural rule.  This is only
    // used for currency plural formatting.  Currency plural name is not a fixed
    // static one, it is a dynamic name based on the currency plural count.  So, the
    // affixes need to be expanded here.  For other cases, the affix is a static one
    // based on pattern alone, and it is already expanded during applying pattern, or
    // setDecimalFormatSymbols, or setCurrency.
    expandAffixAdjustWidth(pluralCount);
    return subformat(result, fieldPosition, isNegative, isInteger, parseAttr);
}
项目:fitnotifications    文件:DecimalFormat.java   
private final void addPadding(StringBuffer result, FieldPosition fieldPosition, int prefixLen,
                              int suffixLen) {
    if (formatWidth > 0) {
        int len = formatWidth - result.length();
        if (len > 0) {
            char[] padding = new char[len];
            for (int i = 0; i < len; ++i) {
                padding[i] = pad;
            }
            switch (padPosition) {
            case PAD_AFTER_PREFIX:
                result.insert(prefixLen, padding);
                break;
            case PAD_BEFORE_PREFIX:
                result.insert(0, padding);
                break;
            case PAD_BEFORE_SUFFIX:
                result.insert(result.length() - suffixLen, padding);
                break;
            case PAD_AFTER_SUFFIX:
                result.append(padding);
                break;
            }
            if (padPosition == PAD_BEFORE_PREFIX || padPosition == PAD_AFTER_PREFIX) {
                fieldPosition.setBeginIndex(fieldPosition.getBeginIndex() + len);
                fieldPosition.setEndIndex(fieldPosition.getEndIndex() + len);
            }
        }
    }
}
项目:fitnotifications    文件:MessageFormat.java   
private FieldPosition updateMetaData(AppendableWrapper dest, int prevLength,
                                     FieldPosition fp, Object argId) {
    if (dest.attributes != null && prevLength < dest.length) {
        dest.attributes.add(new AttributeAndPosition(argId, prevLength, dest.length));
    }
    if (fp != null && Field.ARGUMENT.equals(fp.getFieldAttribute())) {
        fp.setBeginIndex(prevLength);
        fp.setEndIndex(dest.length);
        return null;
    }
    return fp;
}
项目:fitnotifications    文件:MessageFormat.java   
@SuppressWarnings("unchecked")
private void format(Object arguments, AppendableWrapper result, FieldPosition fp) {
    if ((arguments == null || arguments instanceof Map)) {
        format(null, (Map<String, Object>)arguments, result, fp);
    } else {
        format((Object[])arguments, null, result, fp);
    }
}
项目:fitnotifications    文件:MessageFormat.java   
/**
 * Internal routine used by format.
 *
 * @throws IllegalArgumentException if an argument in the
 *         <code>arguments</code> map is not of the type
 *         expected by the format element(s) that use it.
 */
private void format(Object[] arguments, Map<String, Object> argsMap,
                    AppendableWrapper dest, FieldPosition fp) {
    if (arguments != null && msgPattern.hasNamedArguments()) {
        throw new IllegalArgumentException(
            "This method is not available in MessageFormat objects " +
            "that use alphanumeric argument names.");
    }
    format(0, null, arguments, argsMap, dest, fp);
}
项目: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()};
}
项目:Settings    文件:RFC3339DateFormat.java   
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
  String value = ISO8601Utils.format(date, true);
  toAppendTo.append(value);
  return toAppendTo;
}
项目:RoadLab-Pro    文件:StartMeasurementFragment.java   
protected void initGraph(final boolean isEmpty) {
    int greyColor = getAppResouces().getColor(android.R.color.secondary_text_light_nodisable);
    xyPlot.getGraphWidget().getDomainGridLinePaint().setColor(greyColor);
    xyPlot.getGraphWidget().getRangeSubGridLinePaint().setColor(greyColor);
    xyPlot.getGraphWidget().getRangeGridLinePaint().setColor(greyColor);
    xyPlot.getGraphWidget().getDomainSubGridLinePaint().setColor(greyColor);
    xyPlot.getBackgroundPaint().setColor(Color.WHITE);
    xyPlot.setPlotMargins(0, 0, 0, 0);
    xyPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
    xyPlot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
    xyPlot.getGraphWidget().getCursorLabelBackgroundPaint().setColor(greyColor);
    xyPlot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.WHITE);
    xyPlot.getGraphWidget().getRangeOriginLabelPaint().setColor(greyColor);
    xyPlot.getGraphWidget().getDomainOriginLinePaint().setColor(greyColor);
    xyPlot.getGraphWidget().getRangeOriginLinePaint().setColor(greyColor);
    xyPlot.getGraphWidget().getDomainLabelPaint().setColor(greyColor);
    xyPlot.getGraphWidget().getRangeLabelPaint().setColor(greyColor);
    xyPlot.getDomainLabelWidget().getLabelPaint().setColor(greyColor);
    xyPlot.getRangeLabelWidget().getLabelPaint().setColor(greyColor);
    xyPlot.getDomainLabelWidget().position(0, XLayoutStyle.ABSOLUTE_FROM_CENTER,
            0, YLayoutStyle.RELATIVE_TO_BOTTOM, AnchorPosition.BOTTOM_MIDDLE);
    xyPlot.getTitleWidget().getLabelPaint().setColor(Color.TRANSPARENT);
    xyPlot.getTitleWidget().setVisible(false);
    xyPlot.getLegendWidget().setVisible(false);

    float domainLabelWidth = getAppResouces().getDimensionPixelSize(R.dimen.domainLabelWidth);
    float rangeLabelWidth = getAppResouces().getDimensionPixelSize(R.dimen.rangeLabelWidth);
    float rangeLabelVerticalOffset = getAppResouces().getDimensionPixelSize(R.dimen.rangeLabelVerticalOffset);

    float domainLabelMarginLeft = getAppResouces().getDimensionPixelSize(R.dimen.domainLabelMarginLeft);
    float domainLabelMarginRight = getAppResouces().getDimensionPixelSize(R.dimen.domainLabelMarginRight);
    float rangeLabelMargin = getAppResouces().getDimensionPixelSize(R.dimen.rangeLabelMargin);
    float gridPaddingMargin = getAppResouces().getDimensionPixelSize(R.dimen.gridPaddingMargin);
    float gridPaddingMarginRight = getAppResouces().getDimensionPixelSize(R.dimen.gridPaddingMarginRight);

    xyPlot.getDomainLabelWidget().setMargins(domainLabelMarginLeft, 0, domainLabelMarginRight, 0);
    xyPlot.getRangeLabelWidget().setMargins(rangeLabelMargin, 0, rangeLabelMargin, 0);
    xyPlot.getGraphWidget().setGridPadding(gridPaddingMargin, gridPaddingMargin, gridPaddingMarginRight, gridPaddingMargin);
    xyPlot.getGraphWidget().setDomainLabelWidth(domainLabelWidth);
    xyPlot.getGraphWidget().setRangeLabelWidth(rangeLabelWidth);
    xyPlot.getGraphWidget().setDomainLabelHorizontalOffset(0);
    xyPlot.getGraphWidget().setRangeLabelVerticalOffset(rangeLabelVerticalOffset);

    xyPlot.getDomainLabelWidget().pack();
    xyPlot.getRangeLabelWidget().pack();
    final String secStr = getContext().getString(R.string.seconds);
    final DecimalFormat domainFmt = new DecimalFormat("#.#");
    xyPlot.setDomainValueFormat(new NumberFormat() {
        @Override
        public StringBuffer format(double d, StringBuffer sb, FieldPosition fp) {
            return sb.append(domainFmt.format(d / 50f)).append(secStr);
        }
        @Override
        public StringBuffer format(long l, StringBuffer stringBuffer, FieldPosition fieldPosition) {
            return null;
        }
        @Override
        public Number parse(String s, ParsePosition parsePosition) {
            return null;
        }
    });
    xyPlot.setRangeValueFormat(new DecimalFormat("#.#G"));
    xyPlot.setDomainBoundaries(0, 100, BoundaryMode.FIXED);
    xyPlot.setDomainStepValue(2);
    xyPlot.setRangeStepValue(11);
    xyPlot.setRangeBoundaries(-0.5f, 0.5f, BoundaryMode.FIXED);
    DashPathEffect dashFx = new DashPathEffect(new float[] {PixelUtils.dpToPix(3), PixelUtils.dpToPix(3)}, 0);
    xyPlot.getGraphWidget().getDomainGridLinePaint().setPathEffect(dashFx);
    xyPlot.getGraphWidget().getRangeGridLinePaint().setPathEffect(dashFx);
    setGraphData(null);
}
项目:lttng-scope    文件:DataSpeedWithUnitFormat.java   
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    return super.format(obj, toAppendTo, pos).append(PER_SECOND);
}