⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 decimalformat.java

📁 java源代码 请看看啊 提点宝贵的意见
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
 *         if (locales[i].getCountry().length() == 0) { *            continue; // Skip language-only locales *         } *         System.out.print(locales[i].getDisplayName()); *         switch (j) { *         case 0: *             form = NumberFormat.getInstance(locales[i]); break; *         case 1: *             form = NumberFormat.getIntegerInstance(locales[i]); break; *         case 2: *             form = NumberFormat.getCurrencyInstance(locales[i]); break; *         default: *             form = NumberFormat.getPercentInstance(locales[i]); break; *         } *         if (form instanceof DecimalFormat) { *             System.out.print(": " + ((DecimalFormat) form).toPattern()); *         } *         System.out.print(" -> " + form.format(myNumber)); *         try { *             System.out.println(" -> " + form.parse(form.format(myNumber))); *         } catch (ParseException e) {} *     } * } * </pre></blockquote> * * @see          <a href="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a> * @see          NumberFormat * @see          DecimalFormatSymbols * @see          ParsePosition * @version      1.71 01/23/03 * @author       Mark Davis * @author       Alan Liu */public class DecimalFormat extends NumberFormat {    /**     * Creates a DecimalFormat using the default pattern and symbols     * for the default locale. This is a convenient way to obtain a     * DecimalFormat when internationalization is not the main concern.     * <p>     * To obtain standard formats for a given locale, use the factory methods     * on NumberFormat such as getNumberInstance. These factories will     * return the most appropriate sub-class of NumberFormat for a given     * locale.     *     * @see java.text.NumberFormat#getInstance     * @see java.text.NumberFormat#getNumberInstance     * @see java.text.NumberFormat#getCurrencyInstance     * @see java.text.NumberFormat#getPercentInstance     */    public DecimalFormat() {        Locale def = Locale.getDefault();        // try to get the pattern from the cache        String pattern = (String) cachedLocaleData.get(def);        if (pattern == null) {  /* cache miss */            // Get the pattern for the default locale.            ResourceBundle rb = LocaleData.getLocaleElements(def);            String[] all = rb.getStringArray("NumberPatterns");            pattern = all[0];            /* update cache */            cachedLocaleData.put(def, pattern);        }        // Always applyPattern after the symbols are set        this.symbols = new DecimalFormatSymbols(def);        applyPattern(pattern, false);    }    /**     * Creates a DecimalFormat using the given pattern and the symbols     * for the default locale. This is a convenient way to obtain a     * DecimalFormat when internationalization is not the main concern.     * <p>     * To obtain standard formats for a given locale, use the factory methods     * on NumberFormat such as getNumberInstance. These factories will     * return the most appropriate sub-class of NumberFormat for a given     * locale.     *     * @param pattern A non-localized pattern string.     * @exception NullPointerException if <code>pattern</code> is null     * @exception IllegalArgumentException if the given pattern is invalid.     * @see java.text.NumberFormat#getInstance     * @see java.text.NumberFormat#getNumberInstance     * @see java.text.NumberFormat#getCurrencyInstance     * @see java.text.NumberFormat#getPercentInstance     */    public DecimalFormat(String pattern) {        // Always applyPattern after the symbols are set        this.symbols = new DecimalFormatSymbols(Locale.getDefault());        applyPattern(pattern, false);    }    /**     * Creates a DecimalFormat using the given pattern and symbols.     * Use this constructor when you need to completely customize the     * behavior of the format.     * <p>     * To obtain standard formats for a given     * locale, use the factory methods on NumberFormat such as     * getInstance or getCurrencyInstance. If you need only minor adjustments     * to a standard format, you can modify the format returned by     * a NumberFormat factory method.     *     * @param pattern a non-localized pattern string     * @param symbols the set of symbols to be used     * @exception NullPointerException if any of the given arguments is null     * @exception IllegalArgumentException if the given pattern is invalid     * @see java.text.NumberFormat#getInstance     * @see java.text.NumberFormat#getNumberInstance     * @see java.text.NumberFormat#getCurrencyInstance     * @see java.text.NumberFormat#getPercentInstance     * @see java.text.DecimalFormatSymbols     */    public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {        // Always applyPattern after the symbols are set        this.symbols = (DecimalFormatSymbols)symbols.clone();        applyPattern(pattern, false);    }    // Overrides    /**     * Formats a double to produce a string.     * @param number    The double to format     * @param result    where the text is to be appended     * @param fieldPosition    On input: an alignment field, if desired.     * On output: the offsets of the alignment field.     * @return The formatted number string     * @see java.text.FieldPosition     */    public StringBuffer format(double number, StringBuffer result,                               FieldPosition fieldPosition)    {        fieldPosition.setBeginIndex(0);        fieldPosition.setEndIndex(0);        return format(number, result, fieldPosition.getFieldDelegate());    }    /**     * Formats a double to produce a string.     * @param number    The double to format     * @param result    where the text is to be appended     * @param delegate notified of locations of sub fields     * @return The formatted number string     */    private StringBuffer format(double number, StringBuffer result,                                FieldDelegate delegate) {        if (Double.isNaN(number))        {            int iFieldStart = result.length();            result.append(symbols.getNaN());            delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,                               iFieldStart, result.length(), result);            return result;        }        /* Detecting whether a double is negative is easy with the exception of         * the value -0.0.  This is a double which has a zero mantissa (and         * exponent), but a negative sign bit.  It is semantically distinct from         * a zero with a positive sign bit, and this distinction is important         * to certain kinds of computations.  However, it's a little tricky to         * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0).  How then, you may         * ask, does it behave distinctly from +0.0?  Well, 1/(-0.0) ==         * -Infinity.  Proper detection of -0.0 is needed to deal with the         * issues raised by bugs 4106658, 4106667, and 4147706.  Liu 7/6/98.         */        boolean isNegative = (number < 0.0) || (number == 0.0 && 1/number < 0.0);        if (isNegative) number = -number;        // Do this BEFORE checking to see if value is infinite!        if (multiplier != 1) number *= multiplier;        if (Double.isInfinite(number))        {            if (isNegative) {                append(result, negativePrefix, delegate,                       getNegativePrefixFieldPositions(), Field.SIGN);            }            else {                append(result, positivePrefix, delegate,                       getPositivePrefixFieldPositions(), Field.SIGN);            }            int iFieldStart = result.length();            result.append(symbols.getInfinity());            delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,                               iFieldStart, result.length(), result);            if (isNegative) {                append(result, negativeSuffix, delegate,                       getNegativeSuffixFieldPositions(), Field.SIGN);            }            else {                append(result, positiveSuffix, delegate,                       getPositiveSuffixFieldPositions(), Field.SIGN);            }            return result;        }        // At this point we are guaranteed a nonnegative finite        // number.        synchronized(digitList) {            digitList.set(number, useExponentialNotation ?                      getMaximumIntegerDigits() + getMaximumFractionDigits() :                      getMaximumFractionDigits(),                      !useExponentialNotation);            return subformat(result, delegate, isNegative, false);        }    }    /**     * Format a long to produce a string.     * @param number    The long to format     * @param result    where the text is to be appended     * @param fieldPosition    On input: an alignment field, if desired.     * On output: the offsets of the alignment field.     * @return The formatted number string     * @see java.text.FieldPosition     */    public StringBuffer format(long number, StringBuffer result,                               FieldPosition fieldPosition)    {        fieldPosition.setBeginIndex(0);        fieldPosition.setEndIndex(0);        return format(number, result, fieldPosition.getFieldDelegate());    }    /**     * Format a long to produce a string.     * @param number    The long to format     * @param result    where the text is to be appended     * @param delegate notified of locations of sub fields     * @return The formatted number string     * @see java.text.FieldPosition     */    private StringBuffer format(long number, StringBuffer result,                               FieldDelegate delegate) {        boolean isNegative = (number < 0);        if (isNegative) number = -number;        // In general, long values always represent real finite numbers, so        // we don't have to check for +/- Infinity or NaN.  However, there        // is one case we have to be careful of:  The multiplier can push        // a number near MIN_VALUE or MAX_VALUE outside the legal range.  We        // check for this before multiplying, and if it happens we use doubles        // instead, trading off accuracy for range.        if (multiplier != 1 && multiplier != 0)        {            boolean useDouble = false;            if (number < 0) // This can only happen if number == Long.MIN_VALUE            {                long cutoff = Long.MIN_VALUE / multiplier;                useDouble = (number < cutoff);            }            else            {                long cutoff = Long.MAX_VALUE / multiplier;                useDouble = (number > cutoff);            }            if (useDouble)            {                double dnumber = (double)(isNegative ? -number : number);                return format(dnumber, result, delegate);            }        }        number *= multiplier;        synchronized(digitList) {            digitList.set(number, useExponentialNotation ?                      getMaximumIntegerDigits() + getMaximumFractionDigits() : 0);            return subformat(result, delegate, isNegative, true);        }    }    /**     * Formats an Object producing an <code>AttributedCharacterIterator</code>.     * You can use the returned <code>AttributedCharacterIterator</code>     * to build the resulting String, as well as to determine information     * about the resulting String.     * <p>     * Each attribute key of the AttributedCharacterIterator will be of type     * <code>NumberFormat.Field</code>, with the attribute value being the     * same as the attribute key.     *     * @exception NullPointerException if obj is null.     * @exception IllegalArgumentException when the Format cannot format the     *            given object.     * @param obj The object to format     * @return AttributedCharacterIterator describing the formatted value.     * @since 1.4     */    public AttributedCharacterIterator formatToCharacterIterator(Object obj) {        CharacterIteratorFieldDelegate delegate =                         new CharacterIteratorFieldDelegate();        StringBuffer sb = new StringBuffer();        if (obj instanceof Long ||            (obj instanceof BigInteger &&             ((BigInteger)obj).bitLength() < 64)) {            format(((Number)obj).longValue(), sb, delegate);        }        else if (obj == null) {            throw new NullPointerException(                   "formatToCharacterIterator must be passed non-null object");        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -