Java Code Examples for java.text.NumberFormat#format()

The following examples show how to use java.text.NumberFormat#format() . 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 check out the related API usage on the sidebar.
Example 1
Source File: FormatMicroBenchmark.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: FormatMicroBenchmark.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: RandomPointsProvider.java    From clusterkraf with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: BoxAndWhiskerToolTipGenerator.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: Conversions.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String convert(Double s, Object arg) {
    if (arg instanceof NumberFormat) {
        NumberFormat nf = (NumberFormat) arg;
        return nf.format(s);
    }
    return s.toString();
}
 
Example 6
Source File: Nodes_rectangular_central_generator_primary.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: DataSize.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: UtilAll.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 9
Source File: TieRoundingTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
Source File: AllyStatResult.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
@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};
}
 
Example 11
Source File: CompassFragment.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example 12
Source File: DecodedBitStreamParser.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 13
Source File: UtilAll.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: UtilAll.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: UiUtils.java    From tindroid with Apache License 2.0 5 votes vote down vote up
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];
}
 
Example 16
Source File: MCsvWriter.java    From javamelody with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 17
Source File: SymbolAxis.java    From ccu-historian with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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;

}
 
Example 18
Source File: AppleWorksSpreadSheetFileFilter.java    From AppleCommander with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Build a row reference.
 */
protected String getRowReference(int row) {
	NumberFormat formatter = NumberFormat.getInstance();
	return formatter.format(row);
}
 
Example 19
Source File: CompositeFormat.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: TestUtils.java    From systemds with Apache License 2.0 3 votes vote down vote up
/**
 * <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);
}