FileDocCategorySizeDatePackage
NumberFormat.javaAPI DocphoneME MR2 API (J2ME)22349Wed May 02 18:00:46 BST 2007com.sun.j2me.global

NumberFormat

public class NumberFormat extends Object
NumberFormat has features designed to make it possible to format numbers in any locale. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), percentages (12%), and currency amounts ($123). All of these can be localized.

To obtain a NumberFormat for a specific locale call one of NumberFormat's factory methods, such as:

  • getPercentageInstance(locale)
  • getIntegerInstance(locale)
  • getCurrencyInstance(locale)
  • getDecimalInstance(local)

Usage:

NumberFormat f = NumberFormat.getCurrencyInstance(loc);
StringBuffer sb = f.format(new Double(123.45), new StringBuffer());

Or eventualy it's possible to change number of decimals displayed

NumberFormat f = NumberFormat.getCurrencyInstance(loc);
f.setMaximumFractionDigits(2);
StringBuffer sb = f.format(new Double(123.45559), new StringBuffer());

Fields Summary
private static final String
classname
Class name.
private static final int
DOUBLE_INTEGER_DIGITS
Upper limit on integer digits for a Java double.
private static final int
DOUBLE_FRACTION_DIGITS
Upper limit on fraction digits for a Java double.
public static final char
NONLOCALIZED_PERCENT_SIGN
Non localized percent sign.
public static final char
UNICODE_INFINITY
Unicode INFINITY character.
public static final int
NUMBERSTYLE
General number.
public static final int
CURRENCYSTYLE
Currency style.
public static final int
PERCENTSTYLE
Percent style.
public static final int
INTEGERSTYLE
Integer style.
private NumberFormatSymbols
symbols
Holds initialized instance of DecimalFormatSymbols which encapsulate locale dependent informations like currency symbol, percent symbol etc.
private boolean
isCurrencyFormat
Is this NumberFormat instance for currency formatting?
private boolean
isPercentageFormat
Is this NumberFormat instance of percentage formatting?
private DigitList
digitList
Digit list does most of formatting work.
private int
style
Style of NumberFormat. Possible styles are:
  • {@link #NUMBERSTYLE}
  • {@link #CURRENCYSTYLE}
  • {@link #PERCENTSTYLE}
  • {@link #INTEGERSTYLE}
Constructors Summary
public NumberFormat(int style, NumberFormatSymbols symbols)
Create NumberFormat with given number pattern and set of locale numeric symbols.

param
style the style of NumberFormat
  • {@link #NUMBERSTYLE}
  • {@link #CURRENCYSTYLE}
  • {@link #PERCENTSTYLE}
  • {@link #INTEGERSTYLE}
param
symbols NumberFormatSymbols identifying numbers formatting for given locale.



                                                                                                   
         
        this.style = style;
        this.symbols = symbols;
        isCurrencyFormat = (style == CURRENCYSTYLE);
        isPercentageFormat = (style == PERCENTSTYLE);
        applySymbols();
        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_JSR238,
                           classname + ": " +
                           "NumberFormat created\n" +
                           "style is " + style + "\n" +
                           "symbols is " + symbols);
        }
    
Methods Summary
private voidapplySymbols()
Check if some attributes of NumberFormatSymbols are undefined and replace them with default values.

        if (symbols != null) {
            if (symbols.maximumIntegerDigits[style] == -1) {
                symbols.maximumIntegerDigits[style] = DOUBLE_INTEGER_DIGITS;
            }
            if (symbols.maximumFractionDigits[style] == -1) {
                symbols.maximumFractionDigits[style] = DOUBLE_FRACTION_DIGITS;
            }
        }
    
public java.lang.Stringformat(long value)
Method formats long.

param
value long number to format
return
formatted long number

        return format(new Long(value));
    
public java.lang.Stringformat(double value)
Method formats double.

param
value double value to format
return
formatted double number

        if (symbols != null) {
            if (Double.isNaN(value)) {
                return symbols.NaN;
            }
            if (Double.isInfinite(value)) {
                String prefix = (value > 0.0) ? "" : symbols.negativePrefix[style];
                String suffix = (value > 0.0) ? "" : symbols.negativeSuffix[style];
                return prefix + symbols.infinity + suffix;
            }
        } else {
            if (Double.isNaN(value)) {
                return "NaN";
            }
            if (Double.isInfinite(value)) {
                String prefix = (value > 0.0) ? "" : "-";
                return prefix + UNICODE_INFINITY;
            }
        }
        return format(new Double(value));
    
public java.lang.Stringformat(int value)
Method formats integer.

param
value integer value to format
return
formatted integer number

        return format(new Long(value));
    
public java.lang.Stringformat(float value)
Method formats float.

param
value float value to format
return
formatted float number

        return format((double)value);
    
protected java.lang.Stringformat(java.lang.Object o)
Does formatting. Result is appended to parameter StringBuffer appendTo.

param
o object to format
return
buffer with appended formatted text

        StringBuffer appendTo = new StringBuffer();
        if (o == null) {
            return "";
        }
        if (symbols != null) {
            if (o instanceof Double) {
                format(((Double) o).doubleValue(), appendTo);
            }
            if (o instanceof Long) {
                format(((Long) o).longValue(), appendTo);
            }
        } else {
            if (isPercentageFormat) {
                if (o instanceof Double) {
                    appendTo.append(Double.toString(
                                    ((Double)o).doubleValue() * 100.0));
                } else if (o instanceof Long) {
                    long value = ((Long) o).longValue();
                    appendTo.append(Long.toString(value));
                    if (value != 0) appendTo.append("00");
                }
                appendTo.append(NONLOCALIZED_PERCENT_SIGN);
            } else {
                return o.toString();
            }
        }
        return appendTo.toString();
    
private java.lang.StringBufferformat(double number, java.lang.StringBuffer result)
Formats double number.

param
number the double number to formatt
param
result formatted number
return
buffer with appended formatted number

        if (Double.isNaN(number)) {
            result.append(symbols.NaN);
            return result;
        }
        boolean isNegative = (number < 0.0) ||
                             (number == 0.0 && 1 / number < 0.0);
        if (isNegative) {
            number = -number;
        }

        if (symbols.multiplier[style] != 1) {
            number *= symbols.multiplier[style];
        }

        if (Double.isInfinite(number)) {
            if (isNegative) {
                result.append(symbols.negativePrefix[style]);
            } else {
                result.append(symbols.positivePrefix[style]);
            }
            result.append(symbols.infinity);

            if (isNegative) {
                result.append(symbols.negativeSuffix[style]);
            } else {
                result.append(symbols.positiveSuffix[style]);
            }
            return result;
        }

        digitList.set(number, symbols.maximumFractionDigits[style]);
        result = subformat(result, isNegative, false);

        return result;
    
private java.lang.StringBufferformat(long number, java.lang.StringBuffer result)
Format a long to produce a string.

param
number The long to format
param
result where the text is to be appended
return
The formatted number

        boolean isNegative = (number < 0);
        if (isNegative) {
            number = -number;
        }

        if (symbols.multiplier[style] != 1 &&
                symbols.multiplier[style] != 0) {
            boolean useDouble = false;

            if (number < 0) {
                //  This can only happen if number == Long.MIN_VALUE

                long cutoff = Long.MIN_VALUE / symbols.multiplier[style];
                useDouble = (number < cutoff);
            } else {
                long cutoff = Long.MAX_VALUE / symbols.multiplier[style];
                useDouble = (number > cutoff);
            }

            if (useDouble) {
                double dnumber = (double) (isNegative ? -number : number);
                return format(dnumber, result);
            }
        }

        number *= symbols.multiplier[style];
        synchronized (digitList) {
            digitList.set(number, 0);

            return subformat(result, isNegative, true);
        }
    
public java.lang.StringgetCurrencySymbolForCode(java.lang.String currencyCode)
Lookup table of supported currencies for appropriate symbol.

param
currencyCode code ISO 4217.
return
currency symbol or null if none was found.

    	if (symbols != null && symbols.currencies != null){
	        for (int i = 0; i < symbols.currencies.length; i++) {
	            if (symbols.currencies[i].length>0 && symbols.currencies[i][0].equals(currencyCode))
	                if (symbols.currencies[i].length>1){ 
	                	return  symbols.currencies[i][1];
	                } else {
	                	return null;
	                }
	        }
    	}
        return null;
    
public intgetMaximumFractionDigits()
How many decimals is used to display number.

return
maximum number of decimals or -1 if non-localized formatting is used.
see
#setMaximumFractionDigits

        return (symbols != null) ?
                symbols.maximumFractionDigits[style] :
                -1;
    
public intgetMinimumFractionDigits()
Get minimum of decimals used to display number.

return
minimum number of decimals or -1 if non-localized formatting is used.
see
#setMinimumFractionDigits

        return (symbols != null) ?
                symbols.minimumFractionDigits[style] :
                -1;
    
public intgetMinimumIntegerDigits()
Gets minimum integer digits.

return
number minimum of integer digits
see
#setMinimumIntegerDigits

        return (symbols != null) ?
                symbols.minimumIntegerDigits[style] :
                -1;
    
public intgetMultiplier()
Gets actual multilier used by this locale for this number style. Usually (1 or 100).

return
the multiplier
see
#setMultiplier

        return (symbols != null) ? symbols.multiplier[style] : 1;
    
private java.lang.StringreplSubStr(java.lang.String str, java.lang.String oldVal, java.lang.String newVal)
Replaces substring in the string onto new string.

param
str the changed string
param
oldVal the replaced substring
param
newVal the replacing string
return
changed string

        String res = str;
        if (str.length() > 0) {
            int pos = str.indexOf(oldVal);
            if (pos >= 0) {
                res = str.substring(0, pos);
                res = res.concat(newVal);
                res = res.concat(str.substring(pos + oldVal.length()));
                return res;
            }
        }
        return res;
    
public java.lang.StringsetCurrencySymbol(java.lang.String symbol)
Sets currency symbol.

param
symbol the currency symbol
return
previously used currency symbol

    	String oldsymbol = null;
        if (isCurrencyFormat) {
            if (symbols != null) {
            	oldsymbol = symbols.currencySymbol;
                if (!symbol.equals(symbols.currencySymbol)) {
                    symbols.currencySymbol = symbol;
                    symbols.suffixes[style] =
                            replSubStr(symbols.suffixes[style], oldsymbol,
                                       symbol);
                    symbols.prefixes[style] =
                            replSubStr(symbols.prefixes[style], oldsymbol,
                                       symbol);
                    symbols.negativeSuffix[style] =
                            replSubStr(symbols.negativeSuffix[style], oldsymbol,
                                       symbol);
                    symbols.negativePrefix[style] =
                            replSubStr(symbols.negativePrefix[style], oldsymbol,
                                       symbol);
                    symbols.positiveSuffix[style] =
                            replSubStr(symbols.positiveSuffix[style], oldsymbol,
                                       symbol);
                    symbols.positivePrefix[style] =
                            replSubStr(symbols.positivePrefix[style], oldsymbol,
                                       symbol);
                }
            }
        }
        return oldsymbol;
    
public voidsetGroupingUsed(boolean used)
Sets if grouping is used.

param
used true if grouping should be used

        if (symbols != null) {
            symbols.groupingUsed = used;
        }
    
public voidsetMaximumFractionDigits(int count)
Set maximal number of decimals to be displayed.

param
count number of decimals to display
see
#getMaximumFractionDigits

        if (symbols != null &&
                count <= DOUBLE_FRACTION_DIGITS &&
            count >= 0 &&
                style != INTEGERSTYLE) {
            symbols.maximumFractionDigits[style] = count;
            if (symbols.minimumFractionDigits[style] < count) {
                symbols.minimumFractionDigits[style] = count;
            }
        }
    
public voidsetMinimumFractionDigits(int count)
Sets minimum number of decimals to be displayed.

param
count minimum number of decimals to display
see
#getMinimumFractionDigits

        if (symbols != null &&
                count >= 0 &&
                style != INTEGERSTYLE) {
            symbols.minimumFractionDigits[style] = count;
            if (count > symbols.maximumFractionDigits[style]) {
                symbols.maximumFractionDigits[style] = count;
            }
        }
    
public voidsetMinimumIntegerDigits(int count)
Sets minimum integer digits.

param
count the count of digits
see
#getMinimumIntegerDigits

        if (symbols != null && count > 0) {
            symbols.minimumIntegerDigits[style] = count;
        }
    
public voidsetMultiplier(int multiplier)
Sets multiplier to different value than symbols for this locale do.

param
multiplier new value for multiplier;
see
#getMultiplier

        if (symbols != null) {
            symbols.multiplier[style] = multiplier;
        }
    
private java.lang.StringBuffersubformat(java.lang.StringBuffer result, boolean isNegative, boolean isInteger)
Formats content of DigitList.

param
result buffer to append formatted number to
param
isNegative true if number is negative
param
isInteger true if integer number will be formatted
return
buffer with appended formatted number


        char zero = symbols.zeroDigit;
        int zeroDelta = zero - '0";
        //  '0' is the DigitList representation of zero
        char grouping = symbols.groupingSeparator;
        char decimal = isCurrencyFormat ?
                symbols.monetarySeparator :
                symbols.decimalSeparator;

        if (digitList.isZero()) {
            digitList.decimalAt = 0;
            //  Normalize
        }

        int fieldStart = result.length();

        if (isNegative) {
            result.append(symbols.negativePrefix[style]);
        } else {
            result.append(symbols.positivePrefix[style]);
        }

        String prefix = symbols.prefixes[style];
        result.append(prefix);

        int count = symbols.minimumIntegerDigits[style];
        int digitIndex = 0;
        //  Index into digitList.fDigits[]
        if (digitList.decimalAt > 0 && count < digitList.decimalAt) {
            count = digitList.decimalAt;
        }

        if (count > symbols.maximumIntegerDigits[style]) {
            count = symbols.maximumIntegerDigits[style];
            digitIndex = digitList.decimalAt - count;
        }

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_JSR238,
                           classname + " :" +
                           "grouping used " + symbols.groupingUsed + "\n" +
                           "grouping separator \"" + grouping + "\"\n" +
                           "decimal separator \"" + decimal + "\"\n" +
                           "digit count " + count);
        }

        int sizeBeforeIntegerPart = result.length();
        for (int i = count - 1; i >= 0; --i) {
            if (i < digitList.decimalAt && digitIndex < digitList.count) {
                //  Output a real digit
                result.append((char) (digitList.digits[digitIndex++] +
                                      zeroDelta));
            } else {
                //  Output a leading zero
                result.append(zero);
            }

            //  Output grouping separator if necessary.  Don't output a
            //  grouping separator if i==0 though; that's at the end of
            //  the integer part.
            if (symbols.groupingUsed && i > 0 &&
                    (symbols.groupingCount != 0) &&
                    (i % symbols.groupingCount == 0)) {
                int gStart = result.length();
                result.append(grouping);
                if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                    Logging.report(Logging.INFORMATION, LogChannels.LC_JSR238,
                                   classname + ": " +
                                   "add grouping at " + (digitIndex-1));
                }
            }
        }// for

        boolean fractionPresent = (symbols.minimumFractionDigits[style] > 0) ||
                (!isInteger && digitIndex < digitList.count);

        if (!fractionPresent && result.length() == sizeBeforeIntegerPart) {
            result.append(zero);
        }
        //  Output the decimal separator if we always do so.
        int sStart = result.length();
        if (symbols.decimalSeparatorAlwaysShown || fractionPresent) {
            result.append(decimal);
        }

        for (int i = 0; i < symbols.maximumFractionDigits[style]; ++i) {
            if (i >= symbols.minimumFractionDigits[style] &&
                    (isInteger || digitIndex >= digitList.count)) {
                break;
            }

            if (-1 - i > (digitList.decimalAt - 1)) {
                result.append(zero);
                continue;
            }

            if (!isInteger && digitIndex < digitList.count) {
                result.append((char) (digitList.digits[digitIndex++] +
                                      zeroDelta));
            } else {
                result.append(zero);
            }
        }

        String suffix = symbols.suffixes[style];
        result.append(suffix);

        if (isNegative) {
            result.append(symbols.negativeSuffix[style]);
        } else {
            result.append(symbols.positiveSuffix[style]);
        }

        return result;