java.text.NumberFormat#format ( )源码实例Demo

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

/**
 * Creates the array of items that can be passed to the
 * {@link MessageFormat} class for creating labels.
 *
 * @param dataset  the dataset (<code>null</code> not permitted).
 * @param series  the series (zero-based index).
 * @param item  the item (zero-based index).
 *
 * @return The items (never <code>null</code>).
 */
@Override
protected Object[] createItemArray(CategoryDataset dataset, int series,
                                   int item) {
    Object[] result = new Object[8];
    result[0] = dataset.getRowKey(series);
    Number y = dataset.getValue(series, item);
    NumberFormat formatter = getNumberFormat();
    result[1] = formatter.format(y);
    if (dataset instanceof BoxAndWhiskerCategoryDataset) {
        BoxAndWhiskerCategoryDataset d
            = (BoxAndWhiskerCategoryDataset) dataset;
        result[2] = formatter.format(d.getMeanValue(series, item));
        result[3] = formatter.format(d.getMedianValue(series, item));
        result[4] = formatter.format(d.getMinRegularValue(series, item));
        result[5] = formatter.format(d.getMaxRegularValue(series, item));
        result[6] = formatter.format(d.getQ1Value(series, item));
        result[7] = formatter.format(d.getQ3Value(series, item));
    }
    return result;
}
 
源代码2 项目: clusterkraf   文件: RandomPointsProvider.java
@Override
protected ArrayList<InputPoint> doInBackground(Integer... params) {
	ArrayList<InputPoint> inputPoints = new ArrayList<InputPoint>(params[0]);
	NumberFormat nf = NumberFormat.getInstance();
	for (int i = 0; i < params[0]; i++) {
		MarkerData marker;
		if (i == 0) {
			marker = MarkerData.TwoToasters;
		} else {
			marker = new MarkerData(getRandomLatLng(), nf.format(i));
		}
		InputPoint point = new InputPoint(marker.getLatLng(), marker);
		inputPoints.add(point);
	}
	return inputPoints;
}
 
源代码3 项目: hottub   文件: FormatMicroBenchmark.java
private static String benchFormatFractionalAllNines(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double fractionalEven = isCurrency ?  0.993000001 : 0.99930000001;
    double fractionalOdd  = isCurrency ?  0.996000001 : 0.99960000001;
    double fractional;
    double d;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        if ((j & 1) == 0)
            fractional = fractionalEven;
        else
            fractional = fractionalOdd;
        if ( j >= 0)
            d = (double ) j + fractional;
        else d = (double) j - fractional;
        str = nf.format(d);
    }
    return str;
}
 
源代码4 项目: TencentKona-8   文件: FormatMicroBenchmark.java
private static String benchFormatAllNines(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double[] decimaAllNines =
        {9.9993, 99.9993, 999.9993, 9999.9993, 99999.9993,
         999999.9993, 9999999.9993, 99999999.9993, 999999999.9993};
    double[] currencyAllNines =
        {9.993, 99.993, 999.993, 9999.993, 99999.993,
         999999.993, 9999999.993, 99999999.993, 999999999.993};
    double[] valuesArray = (isCurrency) ? currencyAllNines : decimaAllNines;
    double seed = 1.0 / (double) MAX_RANGE;
    double d;
    int id;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        id = (j >=  0) ? j % 9 : -j % 9;
        if ((j & 1) == 0)
            d = valuesArray[id] + id * seed;
        else
            d = valuesArray[id] - id * seed;
        str = nf.format(d);
    }
    return str;
}
 
源代码5 项目: jdk8u60   文件: TieRoundingTest.java
static void formatOutputTestObject(NumberFormat nf,
                                   Object someNumber,
                                   String tiePosition,
                                   String inputDigits,
                                   String expectedOutput) {

    int mfd = nf.getMaximumFractionDigits();
    RoundingMode rm = nf.getRoundingMode();
    String result = nf.format(someNumber);

    if (!result.equals(expectedOutput)) {
        System.out.println();
        System.out.println("========================================");
        System.out.println("***Failure : error formatting value from string : " +
                           inputDigits);
        System.out.println("NumberFormat pattern is  : " +
                           ((DecimalFormat ) nf).toPattern());
        System.out.println("Maximum number of fractional digits : " + mfd);
        System.out.println("Fractional rounding digit : " + (mfd + 1));
        System.out.println("Position of value relative to tie : " + tiePosition);
        System.out.println("Rounding Mode : " + rm);
        System.out.println("Number self output representation: " + someNumber);
        System.out.println(
           "Error. Formatted result different from expected." +
           "\nExpected output is : \"" + expectedOutput + "\"" +
           "\nFormated output is : \"" + result + "\"");
        System.out.println("========================================");
        System.out.println();

        errorCounter++;
        allPassed = false;
    } else {
        testCounter++;
        System.out.print("Success. Number input :" + inputDigits);
        System.out.print(", rounding : " + rm);
        System.out.print(", fract digits : " + mfd);
        System.out.print(", tie position : " + tiePosition);
        System.out.println(", expected : " + expectedOutput);
    }
}
 
源代码6 项目: tindroid   文件: UiUtils.java
static String bytesToHumanSize(long bytes) {
    if (bytes <= 0) {
        return "0 Bytes";
    }

    String[] sizes = new String[]{"Bytes", "KB", "MB", "GB", "TB"};
    int bucket = (63 - Long.numberOfLeadingZeros(bytes)) / 10;
    double count = bytes / Math.pow(1024, bucket);
    int roundTo = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;
    NumberFormat fmt = DecimalFormat.getInstance();
    fmt.setMaximumFractionDigits(roundTo);
    return fmt.format(count) + " " + sizes[bucket];
}
 
源代码7 项目: rocketmq   文件: UtilAll.java
public static String offset2FileName(final long offset) {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumIntegerDigits(20);
    nf.setMaximumFractionDigits(0);
    nf.setGroupingUsed(false);
    return nf.format(offset);
}
 
源代码8 项目: rocketmq   文件: UtilAll.java
public static String offset2FileName(final long offset) {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumIntegerDigits(20);
    nf.setMaximumFractionDigits(0);
    nf.setGroupingUsed(false);
    return nf.format(offset);
}
 
源代码9 项目: RipplePower   文件: DecodedBitStreamParser.java
static DecoderResult decode(byte[] bytes, int mode) {
	StringBuilder result = new StringBuilder(144);
	switch (mode) {
	case 2:
	case 3:
		String postcode;
		if (mode == 2) {
			int pc = getPostCode2(bytes);
			NumberFormat df = new DecimalFormat("0000000000".substring(0, getPostCode2Length(bytes)));
			postcode = df.format(pc);
		} else {
			postcode = getPostCode3(bytes);
		}
		String country = THREE_DIGITS.format(getCountry(bytes));
		String service = THREE_DIGITS.format(getServiceClass(bytes));
		result.append(getMessage(bytes, 10, 84));
		if (result.toString().startsWith("[)>" + RS + "01" + GS)) {
			result.insert(9, postcode + GS + country + GS + service + GS);
		} else {
			result.insert(0, postcode + GS + country + GS + service + GS);
		}
		break;
	case 4:
		result.append(getMessage(bytes, 1, 93));
		break;
	case 5:
		result.append(getMessage(bytes, 1, 77));
		break;
	}
	return new DecoderResult(bytes, result.toString(), null, String.valueOf(mode));
}
 
源代码10 项目: android_maplibui   文件: CompassFragment.java
public static String formatNumber(Object value, int max, int min) {
    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumFractionDigits(max);
    f.setMinimumFractionDigits(min);
    f.setGroupingUsed(false);

    try {
        return f.format(value);
    } catch (IllegalArgumentException e) {
        return e.getLocalizedMessage();
    }
}
 
源代码11 项目: dsworkbench   文件: AllyStatResult.java
@Override
public String[] getReplacements(boolean pExtended) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(0);
    nf.setMinimumFractionDigits(0);
    String valAllyName = (ally != null) ? ally.getName() : "unbekannt";
    String valAllyTag = (ally != null) ? ally.getTag() : "unbekannt";
    String valAttackers = nf.format(getAttackers());
    String valAttacks = nf.format(attacks);
    String valOffs = nf.format(offs);
    String valSnobs = nf.format(snobs);
    String valFakes = nf.format(fakes);
    String valEnoblements = nf.format(enoblements);
    String valKills = nf.format(kills);
    String valKillsFarm = nf.format(killsAsFarm);
    String valLosses = nf.format(losses);
    String valLossesFarm = nf.format(lossesAsFarm);
    String valWallDestruction = nf.format(wallDestruction);
    String valBuildingDestruction = nf.format(buildingDestruction);
    nf.setMinimumFractionDigits(2);
    nf.setMaximumFractionDigits(2);
    String valKillsPercent = (overallKills == 0) ? "0.0 %" : nf.format(100 * kills / (double) overallKills) + " %";
    String valLossesPercent = (overallLosses == 0) ? "0.0 %" : nf.format(100 * losses / (double) overallLosses) + " %";

    return new String[]{valAllyName, valAllyTag, valAttackers, valAttacks, valOffs, valSnobs, valFakes, valEnoblements, valKills, valKillsFarm,
                valKillsPercent, valLosses, valLossesFarm, valLossesPercent, valWallDestruction, valBuildingDestruction};
}
 
源代码12 项目: hortonmachine   文件: Conversions.java
@Override
public String convert(Double s, Object arg) {
    if (arg instanceof NumberFormat) {
        NumberFormat nf = (NumberFormat) arg;
        return nf.format(s);
    }
    return s.toString();
}
 
源代码13 项目: rocketmq_trans_message   文件: UtilAll.java
public static String offset2FileName(final long offset) {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumIntegerDigits(20);
    nf.setMaximumFractionDigits(0);
    nf.setGroupingUsed(false);
    return nf.format(offset);
}
 
源代码14 项目: haven-platform   文件: DataSize.java
public static String toString(long src) {
    if(src == 0) {
        return "0";
    }
    long i;
    {
        long tmp = src;
        if(tmp < 0) {
            tmp = ~tmp + 1;
        }
        i = Long.numberOfTrailingZeros(Long.highestOneBit(tmp));
    }
    NumberFormat formatter = new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.ROOT));
    double rem = src;
    if(i < 10) {
        return formatter.format(rem);
    }
    String suff;
    if(i < 20) {
        rem /= KiB;
        suff = "KiB";
    } else if(i < 30) {
        rem /= MiB;
        suff = "MiB";
    } else if(i < 40) {
        rem /= GiB;
        suff = "GiB";
    } else {
        rem /= TiB;
        suff = "TiB";
    }
    return formatter.format(rem) + suff;
}
 
static String getCompleteLine(String node_code, int node_type,
        String wlan_code, double x, double y, double z, int primary_channel,
        int min_channel_allowed, int max_channel_allowed, int channel_bonding_model, double traffic_load) {

    // Round position coordinates to limited number of decimals
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.UK);
    nf.setGroupingUsed(true);
    nf.setMaximumFractionDigits(4);

    String line = node_code + CSV_SEPARATOR
            + node_type + CSV_SEPARATOR
            + wlan_code + CSV_SEPARATOR
            + destination_id + CSV_SEPARATOR
            + nf.format(x) + CSV_SEPARATOR
            + nf.format(y) + CSV_SEPARATOR
            + nf.format(z) + CSV_SEPARATOR
            + primary_channel + CSV_SEPARATOR
            + min_channel_allowed + CSV_SEPARATOR
            + max_channel_allowed + CSV_SEPARATOR
            + cont_wind + CSV_SEPARATOR // CW
            + cont_wind_stage + CSV_SEPARATOR // CW's max stage
            + tpc_min + CSV_SEPARATOR
            + tpc_default + CSV_SEPARATOR
            + tpc_max + CSV_SEPARATOR
            + cca_min + CSV_SEPARATOR
            + cca_default + CSV_SEPARATOR
            + cca_max + CSV_SEPARATOR
            + tx_antenna_gain + CSV_SEPARATOR
            + rx_antenna_gain + CSV_SEPARATOR
            + channel_bonding_model + CSV_SEPARATOR
            + modulation_default + CSV_SEPARATOR
            + central_freq + CSV_SEPARATOR
            + lambda + CSV_SEPARATOR
            + ieee_protocol + CSV_SEPARATOR
            + traffic_load;

    return line;
}
 
源代码16 项目: javamelody   文件: MCsvWriter.java
/**
 * Exporte une JTable dans un fichier au format csv pour double-clique. (séparateur ',', formats nombres et dates US).
 *
 * @param table
 *           MBasicTable
 * @param outputStream
 *           OutputStream
 * @param dateFormat
 *           DateFormat
 * @throws IOException
 *            Erreur disque
 */
protected void writeCsv(final MBasicTable table, final OutputStream outputStream,
		final DateFormat dateFormat) throws IOException {
	// récupération des informations utiles
	final int columnCount = table.getColumnModel().getColumnCount();
	final int rowCount = table.getRowCount();
	final String charset = System.getProperty("file.encoding");
	final Writer out = new OutputStreamWriter(outputStream, charset);

	final char csvSeparator = CSV_SEPARATOR;
	// le séparateur des .csv (',' à l'américaine)
	final NumberFormat decimalFormat = NumberFormat.getInstance(Locale.US);
	decimalFormat.setGroupingUsed(false);
	final String eol = System.getProperty("line.separator");

	// titres des colonnes
	writeCsvHeader(table, out, csvSeparator);

	// les données proprement dites (ligne par ligne puis colonne par colonne)
	Object value;
	String text;
	for (int k = 0; k < rowCount; k++) {
		for (int i = 0; i < columnCount; i++) {
			value = getValueAt(table, k, i);

			if (value instanceof Number) {
				text = decimalFormat.format(value);
			} else if (value instanceof Date) {
				text = dateFormat.format(value);
			} else if (value instanceof Boolean) {
				text = value.toString();
			} else {
				text = getTextAt(table, k, i);
				text = formatCsv(text, csvSeparator);
			}

			out.write(text);
			if (i < columnCount - 1) {
				out.write(csvSeparator);
			}
		}
		if (k < rowCount - 1) {
			out.write(eol);
		}
	}
	out.flush();
}
 
源代码17 项目: ccu-historian   文件: SymbolAxis.java
/**
 * Calculates the positions of the tick labels for the axis, storing the
 * results in the tick label list (ready for drawing).
 *
 * @param g2  the graphics device.
 * @param dataArea  the area in which the data should be drawn.
 * @param edge  the location of the axis.
 *
 * @return The ticks.
 */
@Override
protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea,
        RectangleEdge edge) {

    List ticks = new java.util.ArrayList();

    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);

    double size = getTickUnit().getSize();
    int count = calculateVisibleTickCount();
    double lowestTickValue = calculateLowestVisibleTickValue();

    double previousDrawnTickLabelPos = 0.0;
    double previousDrawnTickLabelLength = 0.0;

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            double xx = valueToJava2D(currentTickValue, dataArea, edge);
            String tickLabel;
            NumberFormat formatter = getNumberFormatOverride();
            if (formatter != null) {
                tickLabel = formatter.format(currentTickValue);
            }
            else {
                tickLabel = valueToString(currentTickValue);
            }

            // avoid to draw overlapping tick labels
            Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
                    g2.getFontMetrics());
            double tickLabelLength = isVerticalTickLabels()
                    ? bounds.getHeight() : bounds.getWidth();
            boolean tickLabelsOverlapping = false;
            if (i > 0) {
                double avgTickLabelLength = (previousDrawnTickLabelLength
                        + tickLabelLength) / 2.0;
                if (Math.abs(xx - previousDrawnTickLabelPos)
                        < avgTickLabelLength) {
                    tickLabelsOverlapping = true;
                }
            }
            if (tickLabelsOverlapping) {
                tickLabel = ""; // don't draw this tick label
            }
            else {
                // remember these values for next comparison
                previousDrawnTickLabelPos = xx;
                previousDrawnTickLabelLength = tickLabelLength;
            }

            TextAnchor anchor;
            TextAnchor rotationAnchor;
            double angle = 0.0;
            if (isVerticalTickLabels()) {
                anchor = TextAnchor.CENTER_RIGHT;
                rotationAnchor = TextAnchor.CENTER_RIGHT;
                if (edge == RectangleEdge.TOP) {
                    angle = Math.PI / 2.0;
                }
                else {
                    angle = -Math.PI / 2.0;
                }
            }
            else {
                if (edge == RectangleEdge.TOP) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                }
                else {
                    anchor = TextAnchor.TOP_CENTER;
                    rotationAnchor = TextAnchor.TOP_CENTER;
                }
            }
            Tick tick = new NumberTick(new Double(currentTickValue),
                    tickLabel, anchor, rotationAnchor, angle);
            ticks.add(tick);
        }
    }
    return ticks;

}
 
/**
 * Build a row reference.
 */
protected String getRowReference(int row) {
	NumberFormat formatter = NumberFormat.getInstance();
	return formatter.format(row);
}
 
源代码19 项目: systemds   文件: TestUtils.java
/**
 * <p>
 * Returns the string representation of a double value which can be used in
 * a DML script.
 * </p>
 * 
 * @param value
 *            double value
 * @return string representation
 */
public static String getStringRepresentationForDouble(double value) {
	NumberFormat nf = NumberFormat.getInstance(new Locale("EN"));
	nf.setGroupingUsed(false);
	nf.setMinimumFractionDigits(1);
	nf.setMaximumFractionDigits(20);
	return nf.format(value);
}
 
源代码20 项目: astor   文件: CompositeFormat.java
/**
 * Formats a double value to produce a string.  In general, the value is
 * formatted using the formatting rules of <code>format</code>.  There are
 * three exceptions to this:
 * <ol>
 * <li>NaN is formatted as '(NaN)'</li>
 * <li>Positive infinity is formatted as '(Infinity)'</li>
 * <li>Negative infinity is formatted as '(-Infinity)'</li>
 * </ol>
 *
 * @param value the double to format.
 * @param format the format used.
 * @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 static StringBuffer formatDouble(final double value, final NumberFormat format,
                                        final StringBuffer toAppendTo,
                                        final FieldPosition pos) {
    if( Double.isNaN(value) || Double.isInfinite(value) ) {
        toAppendTo.append('(');
        toAppendTo.append(value);
        toAppendTo.append(')');
    } else {
        format.format(value, toAppendTo, pos);
    }
    return toAppendTo;
}