Java Code Examples for java.text.FieldPosition

The following examples show how to use java.text.FieldPosition. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jdk8u_jdk   Source File: DateTimeFormatter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    Objects.requireNonNull(obj, "obj");
    Objects.requireNonNull(toAppendTo, "toAppendTo");
    Objects.requireNonNull(pos, "pos");
    if (obj instanceof TemporalAccessor == false) {
        throw new IllegalArgumentException("Format target must implement TemporalAccessor");
    }
    pos.setBeginIndex(0);
    pos.setEndIndex(0);
    try {
        formatter.formatTo((TemporalAccessor) obj, toAppendTo);
    } catch (RuntimeException ex) {
        throw new IllegalArgumentException(ex.getMessage(), ex);
    }
    return toAppendTo;
}
 
Example 2
Source Project: astor   Source File: ComplexFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats a object to produce a string.  <code>obj</code> must be either a
 * {@link Complex} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
        FieldPosition pos) {

    StringBuffer ret = null;

    if (obj instanceof Complex) {
        ret = format( (Complex)obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format( new Complex(((Number)obj).doubleValue(), 0.0),
            toAppendTo, pos);
    } else {
        throw MathRuntimeException.createIllegalArgumentException(
              "cannot format a {0} instance as a complex number",
              obj.getClass().getName());
    }

    return ret;
}
 
Example 3
public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) {
    final double value;
    if (number instanceof Number) {
        value = ((Number)number).doubleValue();
        if (Double.isInfinite(value) || Double.isNaN(value)) {
            return integerFormat.format(number, toAppendTo, pos);
        }
    } else {
        // testBug54786 gets here with a date, so retain previous behaviour
        return integerFormat.format(number, toAppendTo, pos);
    }

    final double abs = Math.abs(value);
    if (abs >= 1E11 || (abs <= 1E-10 && abs > 0)) {
        return scientificFormat.format(number, toAppendTo, pos);
    } else if (Math.floor(value) == value || abs >= 1E10) {
        // integer, or integer portion uses all 11 allowed digits
        return integerFormat.format(number, toAppendTo, pos);
    }
    // Non-integers of non-scientific magnitude are formatted as "up to 11
    // numeric characters, with the decimal point counting as a numeric
    // character". We know there is a decimal point, so limit to 10 digits.
    // https://support.microsoft.com/en-us/kb/65903
    final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue();
    return decimalFormat.format(rounded, toAppendTo, pos);
}
 
Example 4
Source Project: buffer_bci   Source File: HexNumberFormat.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Formats the specified number as a hexadecimal string.  The decimal
 * fraction is ignored.
 *
 * @param number  the number to format.
 * @param toAppendTo  the buffer to append to (ignored here).
 * @param pos  the field position (ignored here).
 *
 * @return The string buffer.
 */
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
        FieldPosition pos) {
    String l_hex = Long.toHexString(number).toUpperCase();

    int l_pad = this.m_numDigits - l_hex.length();
    l_pad = (0 < l_pad) ? l_pad : 0;

    StringBuffer l_extended = new StringBuffer("0x");
    for (int i = 0; i < l_pad; i++) {
        l_extended.append(0);
    }
    l_extended.append(l_hex);

    return l_extended;
}
 
Example 5
Source Project: buffer_bci   Source File: HexNumberFormat.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Formats the specified number as a hexadecimal string.  The decimal
 * fraction is ignored.
 *
 * @param number  the number to format.
 * @param toAppendTo  the buffer to append to (ignored here).
 * @param pos  the field position (ignored here).
 *
 * @return The string buffer.
 */
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
        FieldPosition pos) {
    String l_hex = Long.toHexString(number).toUpperCase();

    int l_pad = this.m_numDigits - l_hex.length();
    l_pad = (0 < l_pad) ? l_pad : 0;

    StringBuffer l_extended = new StringBuffer("0x");
    for (int i = 0; i < l_pad; i++) {
        l_extended.append(0);
    }
    l_extended.append(l_hex);

    return l_extended;
}
 
Example 6
/**
   Appends to <code>sbuf</code> the date in the format "dd MMM yyyy
   HH:mm:ss,SSS" for example, "06 Nov 1994 08:49:37,459".

   @param sbuf the string buffer to write to
*/
public
StringBuffer format(Date date, StringBuffer sbuf,
      FieldPosition fieldPosition) {

  calendar.setTime(date);

  int day = calendar.get(Calendar.DAY_OF_MONTH);
  if(day < 10)
    sbuf.append('0');
  sbuf.append(day);
  sbuf.append(' ');
  sbuf.append(shortMonths[calendar.get(Calendar.MONTH)]);
  sbuf.append(' ');

  int year =  calendar.get(Calendar.YEAR);
  sbuf.append(year);
  sbuf.append(' ');

  return super.format(date, sbuf, fieldPosition);
}
 
Example 7
Source Project: astor   Source File: BigFractionFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer.
 * <code>obj</code> must be either a  {@link BigFraction} object or a
 * {@link BigInteger} object or a {@link Number} object. Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    final StringBuffer ret;
    if (obj instanceof BigFraction) {
        ret = format((BigFraction) obj, toAppendTo, pos);
    } else if (obj instanceof BigInteger) {
        ret = format(new BigFraction((BigInteger) obj), toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format(new BigFraction(((Number) obj).doubleValue()),
                     toAppendTo, pos);
    } else {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot format given object as a fraction number");
    }

    return ret;
}
 
Example 8
Source Project: jdk8u60   Source File: DateTimeFormatter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    Objects.requireNonNull(obj, "obj");
    Objects.requireNonNull(toAppendTo, "toAppendTo");
    Objects.requireNonNull(pos, "pos");
    if (obj instanceof TemporalAccessor == false) {
        throw new IllegalArgumentException("Format target must implement TemporalAccessor");
    }
    pos.setBeginIndex(0);
    pos.setEndIndex(0);
    try {
        formatter.formatTo((TemporalAccessor) obj, toAppendTo);
    } catch (RuntimeException ex) {
        throw new IllegalArgumentException(ex.getMessage(), ex);
    }
    return toAppendTo;
}
 
Example 9
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);

    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);

    return toAppendTo;
}
 
Example 10
Source Project: j2objc   Source File: SimpleDateFormat.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Formats a date or time, which is the standard millis
 * since January 1, 1970, 00:00:00 GMT.
 * <p>Example: using the US locale:
 * "yyyy.MM.dd G 'at' HH:mm:ss zzz" -&gt;&gt; 1996.07.10 AD at 15:08:56 PDT
 * @param cal the calendar whose date-time value is to be formatted into a date-time string
 * @param toAppendTo where the new date-time text is to be appended
 * @param pos the formatting position. On input: an alignment field,
 * if desired. On output: the offsets of the alignment field.
 * @return the formatted date-time string.
 * @see DateFormat
 */
@Override
public StringBuffer format(Calendar cal, StringBuffer toAppendTo,
                           FieldPosition pos) {
    TimeZone backupTZ = null;
    if (cal != calendar && !cal.getType().equals(calendar.getType())) {
        // Different calendar type
        // We use the time and time zone from the input calendar, but
        // do not use the input calendar for field calculation.
        calendar.setTimeInMillis(cal.getTimeInMillis());
        backupTZ = calendar.getTimeZone();
        calendar.setTimeZone(cal.getTimeZone());
        cal = calendar;
    }
    StringBuffer result = format(cal, getContext(DisplayContext.Type.CAPITALIZATION), toAppendTo, pos, null);
    if (backupTZ != null) {
        // Restore the original time zone
        calendar.setTimeZone(backupTZ);
    }
    return result;
}
 
Example 11
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);

    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);

    return toAppendTo;
}
 
Example 12
Source Project: sis   Source File: AngleFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the field position while formatting an angle.
 */
@Test
public void testFieldPosition() {
    final Latitude latitude = new Latitude(FormattedCharacterIteratorTest.LATITUDE_VALUE);
    final AngleFormat f = new AngleFormat("DD°MM′SS.s″", Locale.CANADA);
    final StringBuffer buffer = new StringBuffer();
    for (int i=AngleFormat.DEGREES_FIELD; i<=AngleFormat.HEMISPHERE_FIELD; i++) {
        final AngleFormat.Field field;
        final int start, limit;
        switch (i) {
            case AngleFormat.DEGREES_FIELD:    field = AngleFormat.Field.DEGREES;    start= 0; limit= 3;  break;
            case AngleFormat.MINUTES_FIELD:    field = AngleFormat.Field.MINUTES;    start= 3; limit= 6;  break;
            case AngleFormat.SECONDS_FIELD:    field = AngleFormat.Field.SECONDS;    start= 6; limit=11; break;
            case AngleFormat.HEMISPHERE_FIELD: field = AngleFormat.Field.HEMISPHERE; start=11; limit=12; break;
            default: continue; // Skip the fraction field.
        }
        final FieldPosition pos = new FieldPosition(field);
        assertEquals(FormattedCharacterIteratorTest.LATITUDE_STRING, f.format(latitude, buffer, pos).toString());
        assertSame  ("getFieldAttribute", field, pos.getFieldAttribute());
        assertEquals("getBeginIndex",     start, pos.getBeginIndex());
        assertEquals("getEndIndex",       limit, pos.getEndIndex());
        buffer.setLength(0);
    }
}
 
Example 13
Source Project: astor   Source File: ProperFractionFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats a {@link Fraction} object to produce a string.  The fraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(Fraction fraction, StringBuffer toAppendTo,
        FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    int num = fraction.getNumerator();
    int den = fraction.getDenominator();
    int whole = num / den;
    num = num % den;

    if (whole != 0) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        num = Math.abs(num);
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo,
        pos);

    return toAppendTo;
}
 
Example 14
Source Project: astor   Source File: FractionFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer. <code>obj</code> must be either a 
 * {@link Fraction} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos) {
    StringBuffer ret = null;
    
    if (obj instanceof Fraction) {
        ret = format((Fraction) obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        try {
            ret = format(new Fraction(((Number) obj).doubleValue()),
                         toAppendTo, pos);
        } catch (ConvergenceException ex) {
            throw MathRuntimeException.createIllegalArgumentException(
                "cannot convert given object to a fraction number: {0}",
                ex.getLocalizedMessage());
        }
    } else { 
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot format given object as a fraction number");
    }
    
    return ret;
}
 
Example 15
Source Project: astor   Source File: RealVectorFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats a {@link RealVector} object to produce a string.
 * @param vector the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
public StringBuffer format(RealVector vector, StringBuffer toAppendTo,
                           FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    // format prefix
    toAppendTo.append(prefix);

    // format components
    for (int i = 0; i < vector.getDimension(); ++i) {
        if (i > 0) {
            toAppendTo.append(separator);
        }
        formatDouble(vector.getEntry(i), format, toAppendTo, pos);
    }

    // format suffix
    toAppendTo.append(suffix);

    return toAppendTo;

}
 
Example 16
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);

    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);

    return toAppendTo;
}
 
Example 17
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);

    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);

    return toAppendTo;
}
 
Example 18
Source Project: j2objc   Source File: MeasureFormat.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 19
Source Project: astor   Source File: ProperFractionFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats a {@link Fraction} object to produce a string.  The fraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(Fraction fraction, StringBuffer toAppendTo,
        FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    int num = fraction.getNumerator();
    int den = fraction.getDenominator();
    int whole = num / den;
    num = num % den;

    if (whole != 0) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        num = Math.abs(num);
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo,
        pos);

    return toAppendTo;
}
 
Example 20
Source Project: astor   Source File: ComplexFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats a object to produce a string.  <code>obj</code> must be either a
 * {@link Complex} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
        FieldPosition pos) {

    StringBuffer ret = null;

    if (obj instanceof Complex) {
        ret = format( (Complex)obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format( new Complex(((Number)obj).doubleValue(), 0.0),
            toAppendTo, pos);
    } else {
        throw MathRuntimeException.createIllegalArgumentException(
              "cannot format a {0} instance as a complex number",
              obj.getClass().getName());
    }

    return ret;
}
 
Example 21
Source Project: astor   Source File: BigFractionFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer.
 * <code>obj</code> must be either a  {@link BigFraction} object or a
 * {@link BigInteger} object or a {@link Number} object. Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws MathIllegalArgumentException if <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    final StringBuffer ret;
    if (obj instanceof BigFraction) {
        ret = format((BigFraction) obj, toAppendTo, pos);
    } else if (obj instanceof BigInteger) {
        ret = format(new BigFraction((BigInteger) obj), toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format(new BigFraction(((Number) obj).doubleValue()),
                     toAppendTo, pos);
    } else {
        throw new MathIllegalArgumentException(LocalizedFormats.CANNOT_FORMAT_OBJECT_TO_FRACTION);
    }

    return ret;
}
 
Example 22
Source Project: visualvm   Source File: DisplayableSupport.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StringBuffer format(Object o, StringBuffer b, FieldPosition p) {
    if (ValuesChecker.isNAValue(o)) return b.append(VALUE_NA);
    
    return o instanceof Number ? b.append(NUMBER_FORMAT.format(((Number)o).longValue())).append(dataSuffix) :
           o == null ? b : b.append("<unknown>");
}
 
Example 23
Source Project: astor   Source File: BigFractionFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction is
 * output in improper format.
 *
 * @param BigFraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
public StringBuffer format(final BigFraction BigFraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    getNumeratorFormat().format(BigFraction.getNumerator(), toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(BigFraction.getDenominator(), toAppendTo, pos);

    return toAppendTo;
}
 
Example 24
Source Project: openbd-core   Source File: HexNumberFormat.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String format(int hexNum) throws IllegalArgumentException {
	FieldPosition pos = new FieldPosition(0);
	StringBuffer hexBuf = new StringBuffer(8);

	this.format(new Integer(hexNum), hexBuf, pos);

	return hexBuf.toString();
}
 
Example 25
Source Project: astor   Source File: Vector3DFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Formats a object to produce a string.
 * <p><code>obj</code> must be a  {@link Vector3D} object. Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.</p>
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
                           FieldPosition pos) {

    if (obj instanceof Vector3D) {
        return format( (Vector3D)obj, toAppendTo, pos);
    }

    throw MathRuntimeException.createIllegalArgumentException("cannot format a {0} instance as a 3D vector",
                                                              obj.getClass().getName());

}
 
Example 26
Source Project: beihu-boot   Source File: FastDatePrinter.java    License: Apache License 2.0 5 votes vote down vote up
public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
    if (obj instanceof Date) {
        return format((Date) obj, toAppendTo);
    } else if (obj instanceof Calendar) {
        return format((Calendar) obj, toAppendTo);
    } else if (obj instanceof Long) {
        return format(((Long) obj).longValue(), toAppendTo);
    } else {
        throw new IllegalArgumentException("Unknown class: " +
                (obj == null ? "<null>" : obj.getClass().getName()));
    }
}
 
Example 27
Source Project: astor   Source File: FractionFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Formats a {@link Fraction} object to produce a string.  The fraction is
 * output in improper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
public StringBuffer format(final Fraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    getNumeratorFormat().format(fraction.getNumerator(), toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(fraction.getDenominator(), toAppendTo,
        pos);

    return toAppendTo;
}
 
Example 28
Source Project: coming   Source File: Arja_00134_t.java    License: MIT License 5 votes vote down vote up
/**
 * <p>Formats a <code>Date</code>, <code>Calendar</code> or
 * <code>Long</code> (milliseconds) object.</p>
 * 
 * @param obj  the object to format
 * @param toAppendTo  the buffer to append to
 * @param pos  the position - ignored
 * @return the buffer passed in
 */
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (obj instanceof Date) {
        return format((Date) obj, toAppendTo);
    } else if (obj instanceof Calendar) {
        return format((Calendar) obj, toAppendTo);
    } else if (obj instanceof Long) {
        return format(((Long) obj).longValue(), toAppendTo);
    } else {
        throw new IllegalArgumentException("Unknown class: " +
            (obj == null ? "<null>" : obj.getClass().getName()));
    }
}
 
Example 29
Source Project: kylin-on-parquet-v2   Source File: JDBCResourceSQL.java    License: Apache License 2.0 5 votes vote down vote up
public String getKeyEqualSqlString(boolean fetchContent, boolean fetchTimestamp) {
    final String sql = new MessageFormat(format.getKeyEqualsSql(), Locale.ROOT)
            .format(new Object[] { getSelectList(fetchContent, fetchTimestamp), tableName, metaTableKey },
                    new StringBuffer(), new FieldPosition(0))
            .toString();
    return sql;
}
 
Example 30
Source Project: astor   Source File: FractionFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Formats a {@link Fraction} object to produce a string.  The fraction is
 * output in improper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
public StringBuffer format(final Fraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    getNumeratorFormat().format(fraction.getNumerator(), toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(fraction.getDenominator(), toAppendTo,
        pos);

    return toAppendTo;
}
 
Example 31
Source Project: coming   Source File: Elixir_0010_s.java    License: MIT License 5 votes vote down vote up
/**
 * <p>Formats a <code>Date</code>, <code>Calendar</code> or
 * <code>Long</code> (milliseconds) object.</p>
 * 
 * @param obj  the object to format
 * @param toAppendTo  the buffer to append to
 * @param pos  the position - ignored
 * @return the buffer passed in
 */
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (obj instanceof Date) {
        return format((Date) obj, toAppendTo);
    } else if (obj instanceof Calendar) {
        return format((Calendar) obj, toAppendTo);
    } else if (obj instanceof Long) {
        return format(((Long) obj).longValue(), toAppendTo);
    } else {
        throw new IllegalArgumentException("Unknown class: " +
            (obj == null ? "<null>" : obj.getClass().getName()));
    }
}
 
Example 32
Source Project: fitnotifications   Source File: DateIntervalFormat.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 33
Source Project: lams   Source File: DataFormatter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (emulateCSV) {
        return toAppendTo.append(result.text);
    } else {
        return toAppendTo.append(result.text.trim());
    }
}
 
Example 34
Source Project: SimFix   Source File: 1_FastDateFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Formats a <code>Date</code>, <code>Calendar</code> or
 * <code>Long</code> (milliseconds) object.</p>
 * 
 * @param obj  the object to format
 * @param toAppendTo  the buffer to append to
 * @param pos  the position - ignored
 * @return the buffer passed in
 */
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (obj instanceof Date) {
        return format((Date) obj, toAppendTo);
    } else if (obj instanceof Calendar) {
        return format((Calendar) obj, toAppendTo);
    } else if (obj instanceof Long) {
        return format(((Long) obj).longValue(), toAppendTo);
    } else {
        throw new IllegalArgumentException("Unknown class: " +
            (obj == null ? "<null>" : obj.getClass().getName()));
    }
}
 
Example 35
Source Project: astor   Source File: ComplexFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Format the absolute value of the imaginary part.
 *
 * @param absIm Absolute value of the imaginary part of a complex number.
 * @param toAppendTo where the text is to be appended.
 * @param pos On input: an alignment field, if desired. On output: the
 * offsets of the alignment field.
 * @return the value passed in as toAppendTo.
 */
private StringBuffer formatImaginary(double absIm,
                                     StringBuffer toAppendTo,
                                     FieldPosition pos) {
    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    CompositeFormat.formatDouble(absIm, getImaginaryFormat(), toAppendTo, pos);
    if (toAppendTo.toString().equals("1")) {
        // Remove the character "1" if it is the only one.
        toAppendTo.setLength(0);
    }

    return toAppendTo;
}
 
Example 36
Source Project: astor   Source File: FractionFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Formats a {@link Fraction} object to produce a string.  The fraction is
 * output in improper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
public StringBuffer format(final Fraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    getNumeratorFormat().format(fraction.getNumerator(), toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(fraction.getDenominator(), toAppendTo,
        pos);

    return toAppendTo;
}
 
Example 37
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
{
	final String value = ISO8601Utils.format(date, true);
	toAppendTo.append(value);
	return toAppendTo;
}
 
Example 38
Source Project: lams   Source File: StdDateFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
        FieldPosition fieldPosition)
{
    TimeZone tz = _timezone;
    if (tz == null) {
        tz = DEFAULT_TIMEZONE;
    }
    _format(tz, _locale, date, toAppendTo);
    return toAppendTo;
}
 
Example 39
Source Project: j2objc   Source File: DateIntervalFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void TestTicket9919Setter() {

    // Creating a DateIntervalFormat with a custom DateIntervalInfo
    // object used to corrupt the cache.
    DateIntervalFormat dif = DateIntervalFormat.getInstance(
            "yMd", ULocale.ENGLISH);
    Calendar from = Calendar.getInstance();
    Calendar to = Calendar.getInstance();
    from.set(2013, 3, 26);
    to.set(2013, 3, 28);

    // Save. This is the correct answer
    String expected =
            dif.format(from, to, new StringBuffer(), new FieldPosition(0))
            .toString();

    // Now create a DateIntervalFormat with same skeleton and
    // locale, but with a custom DateIntervalInfo. This used
    // to corrupt the cache.
    DateIntervalInfo dateIntervalInfo =
            new DateIntervalInfo(ULocale.ENGLISH);
    dateIntervalInfo.setIntervalPattern(
            "yMd", Calendar.DATE, "M/d/y \u2013 d");
    DateIntervalFormat bad = DateIntervalFormat.getInstance(
            "yMd", ULocale.ENGLISH);
    bad.setDateIntervalInfo(dateIntervalInfo);

    // Now create a DateIntervalFormat with same skeleton and
    // locale, but with default DateIntervalInfo. The cache should
    // not be corrupted, and we should get the same answer as before.
    dif = DateIntervalFormat.getInstance("yMd", ULocale.ENGLISH);
    assertEquals(
            "Custom DateIntervalInfo objects should not mess up cache",
            expected,
            dif.format(from, to, new StringBuffer(), new FieldPosition(0))
            .toString()); 
}
 
Example 40
Source Project: fitnotifications   Source File: MeasureFormat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}