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

The following examples show how to use java.text.NumberFormat#setMaximumFractionDigits() . 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: VertexMetrics.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public String toPrintableString() {
	NumberFormat nf = NumberFormat.getInstance();

	// format for very small fractional numbers
	NumberFormat ff = NumberFormat.getInstance();
	ff.setMaximumFractionDigits(8);

	return "vertex count: " + nf.format(vertexCount)
		+ "; edge count: " + nf.format(edgeCount)
		+ "; average degree: " + nf.format(getAverageDegree())
		+ "; density: " + ff.format(getDensity())
		+ "; triplet count: " + nf.format(tripletCount)
		+ "; maximum degree: " + nf.format(maximumDegree)
		+ "; maximum triplets: " + nf.format(maximumTriplets);
}
 
Example 2
Source File: Main.java    From algorithms-nutshell-2ed with MIT License 6 votes vote down vote up
public static void main (String []args) {
	LineSweep dba1 = new LineSweep();
	BruteForceAlgorithm dba2 = new BruteForceAlgorithm();
	NumberFormat nf = NumberFormat.getInstance();
	nf.setMaximumFractionDigits(2);
	nf.setGroupingUsed(false);
	
	TrialSuite db1_suite = testSlidingLadder (dba1);
	TrialSuite db2_suite = testSlidingLadder (dba2);
	
	System.out.println("n\tAvgLS\tAvgBF");
	for (int c = 2; c <= 512; c *= 2) {
		System.out.println(c + "\t" + nf.format(Double.valueOf(db1_suite.getAverage(c))) + "\t" 
				+ nf.format(Double.valueOf(db2_suite.getAverage(c))));
	}
}
 
Example 3
Source File: TimeDelta.java    From big-c with Apache License 2.0 5 votes vote down vote up
public String toString() {
	NumberFormat nf=NumberFormat.getInstance(Locale.UK);
	nf.setGroupingUsed(false);
	nf.setMaximumFractionDigits(6);
	String floatsecs=nf.format(total_seconds);
	return String.format("Timedelta: %d days, %d seconds, %d microseconds (total: %s seconds)", days, seconds, microseconds, floatsecs);
}
 
Example 4
Source File: LightMapDialog.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
private CharSequence styleLengthText(@NonNull Context context, double meters, WidgetSettings.LengthUnit units)
{
    NumberFormat formatter = NumberFormat.getInstance();
    formatter.setMinimumFractionDigits(0);
    formatter.setMaximumFractionDigits(2);
    if (meters < Double.POSITIVE_INFINITY)
        return SuntimesUtils.formatAsHeight(context, meters, units, 2, true).toString();
    else return formatter.format(meters);
}
 
Example 5
Source File: LocaleFormatter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Format the passed value according to the rules specified by the given
 * locale.
 *
 * @param aValue
 *        The value to be formatted. May not be <code>null</code>.
 * @param nFractionDigits
 *        The number of fractional digits to use. Must be &ge; 0.
 * @param aDisplayLocale
 *        The locale to be used. May not be <code>null</code>.
 * @return The formatted string.
 */
@Nonnull
public static String getFormatted (@Nonnull final BigDecimal aValue,
                                   @Nonnegative final int nFractionDigits,
                                   @Nonnull final Locale aDisplayLocale)
{
  ValueEnforcer.notNull (aValue, "Value");
  ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale");

  final NumberFormat aNF = NumberFormat.getInstance (aDisplayLocale);
  aNF.setMinimumFractionDigits (nFractionDigits);
  aNF.setMaximumFractionDigits (nFractionDigits);
  return aNF.format (aValue);
}
 
Example 6
Source File: UtilAll.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
/**
 * 将offset转化成字符串形式<br>
 * 左补零对齐至20位
 */
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 7
Source File: DSWorkbenchStatsFrame.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
private void addDataset(String pId, XYDataset pDataset) {
    if (chart == null) {
        setupChart(pId, pDataset);
    } else {
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDataset(plot.getDatasetCount(), pDataset);
        NumberAxis axis = new NumberAxis(pId);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(0);
        axis.setNumberFormatOverride(nf);
        plot.setRangeAxis(plot.getDatasetCount() - 1, axis);
        plot.setRangeAxisLocation(plot.getDatasetCount() - 1, AxisLocation.TOP_OR_LEFT);
        plot.mapDatasetToRangeAxis(plot.getDatasetCount() - 1, plot.getDatasetCount() - 1);
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(0, jShowDataPoints.isSelected());
        plot.setRenderer(plot.getDatasetCount() - 1, renderer);
        renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
        renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
        renderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
        axis.setAxisLinePaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickMarkPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
    }
}
 
Example 8
Source File: ProgressStatistics.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private static String convert(long amount)
{
	NumberFormat fmt = NumberFormat.getInstance();
	if (amount < 1024)
		return fmt.format(amount) + "B"; //$NON-NLS-1$

	fmt.setMaximumFractionDigits(2);
	if (amount < 1024 * 1024)
		return fmt.format(((double) amount) / 1024) + "kB"; //$NON-NLS-1$

	return fmt.format(((double) amount) / (1024 * 1024)) + "MB"; //$NON-NLS-1$
}
 
Example 9
Source File: FormatUtils.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
/**
 * Formats the specified data size in human readable format.
 *
 * @param dataSize Data size in bytes
 * @return Human readable format
 */
public static String formatDataSize(final double dataSize) {
    // initialize the formatter
    final NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);

    // check terabytes
    double dataSizeToFormat = dataSize / BYTES_IN_TERABYTE;
    if (dataSizeToFormat > 1) {
        return format.format(dataSizeToFormat) + " TB";
    }

    // check gigabytes
    dataSizeToFormat = dataSize / BYTES_IN_GIGABYTE;
    if (dataSizeToFormat > 1) {
        return format.format(dataSizeToFormat) + " GB";
    }

    // check megabytes
    dataSizeToFormat = dataSize / BYTES_IN_MEGABYTE;
    if (dataSizeToFormat > 1) {
        return format.format(dataSizeToFormat) + " MB";
    }

    // check kilobytes
    dataSizeToFormat = dataSize / BYTES_IN_KILOBYTE;
    if (dataSizeToFormat > 1) {
        return format.format(dataSizeToFormat) + " KB";
    }

    // default to bytes
    return format.format(dataSize) + " bytes";
}
 
Example 10
Source File: AnalysisResult.java    From hlta with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
	StringBuffer str = new StringBuffer();

	NumberFormat nf = NumberFormat.getInstance();
	nf.setMaximumFractionDigits(0);

	// append latent variable names
	for (Variable latent : _prior.getVariables()) {
		str.append(latent.getName());
		str.append(" ");
	}

	// append latent states and prior distribution
	str.append("[");

	List<Variable> latents = _prior.getVariables();
	int nLatents = _prior.getDimension();
	int[] states = new int[nLatents];
	int card = getLatentCardinality();

	for (int i = 0; i < card; i++) {
		_prior.computeStates(i, states);

		for (int j = 0; j < nLatents; j++) {
			str.append(latents.get(j).getStates().get(states[j]));
		}

		if (i < card - 1) {
			str.append(";");
		}
	}

	str.append("|");

	double[] prior = _prior.getCells();

	for (int i = 0; i < card; i++) {
		str.append(nf.format(prior[i] * 100));

		if (i < card - 1) {
			str.append(";");
		}
	}

	str.append("]: ");

	// append the list of selected manifest variables
	int nManifests = _selectedManifests.size();
	List<Double> pmiSeq = getSelectedPmiSeq();
	List<Double> cmiSeq = getSelectedCmiSeq();

	for (int i = 0; i < nManifests; i++) {
		Variable manifest = _selectedManifests.get(i);

		// append manifest variable name
		str.append(manifest.getName());
		str.append(" [");

		// append class-conditional probability P(X=1|Y=j)
		for (int j = 0; j < card; j++) {
			str
					.append(nf.format(_ccpds.get(j).get(manifest)
							.getCells()[1] * 100));

			if (j < card - 1) {
				str.append(";");
			}
		}

		str.append("|");

		// append pairwise and cumulative information coverage
		str.append(nf.format(pmiSeq.get(i) * 100 / _tmi));
		str.append(";");
		str.append(nf.format(cmiSeq.get(i) * 100 / _tmi));

		str.append("]");
		if (i < nManifests - 1) {
			str.append(", ");
		}
	}

	return str.toString();
}
 
Example 11
Source File: CurrencyFormat.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
static void testFormatting() {
    boolean failed = false;
    Locale[] locales = {
        Locale.US,
        Locale.JAPAN,
        Locale.GERMANY,
        Locale.ITALY,
        new Locale("it", "IT", "EURO") };
    Currency[] currencies = {
        null,
        Currency.getInstance("USD"),
        Currency.getInstance("JPY"),
        Currency.getInstance("DEM"),
        Currency.getInstance("EUR"),
    };
    String[][] expecteds = {
        {"$1,234.56", "$1,234.56", "JPY1,235", "DEM1,234.56", "EUR1,234.56"},
        {"\uFFE51,235", "USD1,234.56", "\uFFE51,235", "DEM1,234.56", "EUR1,234.56"},
        {"1.234,56 \u20AC", "1.234,56 USD", "1.235 JPY", "1.234,56 DM", "1.234,56 \u20AC"},
        {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"},
        {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"},
    };

    for (int i = 0; i < locales.length; i++) {
        Locale locale = locales[i];
        NumberFormat format = NumberFormat.getCurrencyInstance(locale);
        for (int j = 0; j < currencies.length; j++) {
            Currency currency = currencies[j];
            String expected = expecteds[i][j];
            if (currency != null) {
                format.setCurrency(currency);
                int digits = currency.getDefaultFractionDigits();
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            }
            String result = format.format(1234.56);
            if (!result.equals(expected)) {
                failed = true;
                System.out.println("FAIL: Locale " + locale
                    + (currency == null ? ", default currency" : (", currency: " + currency))
                    + ", expected: " + expected
                    + ", actual: " + result);
            }
        }
    }

    if (failed) {
        throw new RuntimeException();
    }
}
 
Example 12
Source File: Vector1DFormatAbstractTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
protected Vector1DFormatAbstractTest() {
    vector1DFormat = Vector1DFormat.getInstance(getLocale());
    final NumberFormat nf = NumberFormat.getInstance(getLocale());
    nf.setMaximumFractionDigits(2);
    vector1DFormatSquare = new Vector1DFormat("[", "]", nf);
}
 
Example 13
Source File: DateUtils.java    From webarchive-commons with Apache License 2.0 4 votes vote down vote up
private static String doubleToString(double val, int maxFractionDigits, int minFractionDigits) {
    NumberFormat f = NumberFormat.getNumberInstance(Locale.US); 
    f.setMaximumFractionDigits(maxFractionDigits);
    f.setMinimumFractionDigits(minFractionDigits);
    return f.format(val); 
}
 
Example 14
Source File: RealMatrixFormatAbstractTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public RealMatrixFormatAbstractTest() {
    realMatrixFormat = RealMatrixFormat.getInstance(getLocale());
    final NumberFormat nf = NumberFormat.getInstance(getLocale());
    nf.setMaximumFractionDigits(2);
    realMatrixFormatOctave = new RealMatrixFormat("[", "]", "", "", "; ", ", ", nf);
}
 
Example 15
Source File: RatingService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   public List<ItemRatingDTO> getRatingCriteriaDtos(Long contentId, Long toolSessionId, Collection<Long> itemIds,
    boolean isCommentsByOtherUsersRequired, Long userId) {

// fail safe - if there are no items, don't try to look anything up! LDEV-4094
if (itemIds == null || itemIds.isEmpty()) {
    return new LinkedList<>();
}

//initial preparations
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
numberFormat.setMaximumFractionDigits(1);
List<RatingCriteria> criterias = getCriteriasByToolContentId(contentId);
boolean isSingleItem = itemIds.size() == 1;
Long singleItemId = isSingleItem ? itemIds.iterator().next() : null;

//handle comments criteria
List<ItemRatingDTO> itemDtos = handleCommentsCriteria(criterias, toolSessionId, itemIds,
	isCommentsByOtherUsersRequired, userId);

//get all data from DB
List<Rating> userRatings = ratingDAO.getRatingsByUser(contentId, userId.intValue());
List<Object[]> itemsStatistics;
if (isSingleItem) {
    itemsStatistics = ratingDAO.getRatingAverageByContentAndItem(contentId, toolSessionId, singleItemId);

    // query DB using itemIds
} else {
    itemsStatistics = ratingDAO.getRatingAverageByContentAndItems(contentId, toolSessionId, itemIds);
}

//handle all criterias except for comments' one
for (ItemRatingDTO itemDto : itemDtos) {
    Long itemId = itemDto.getItemId();
    List<ItemRatingCriteriaDTO> criteriaDtos = new LinkedList<>();
    itemDto.setCriteriaDtos(criteriaDtos);

    for (RatingCriteria criteria : criterias) {
	Long criteriaId = criteria.getRatingCriteriaId();

	//comments' criteria are handled earlier, at the beginning of this function
	if (criteria.getRatingStyle() == 0) {
	    continue;
	}

	ItemRatingCriteriaDTO criteriaDto = new ItemRatingCriteriaDTO();
	criteriaDto.setRatingCriteria(criteria);

	// set user's rating
	Rating userRating = null;
	for (Rating userRatingIter : userRatings) {
	    if (userRatingIter.getItemId().equals(itemId)
		    && userRatingIter.getRatingCriteria().getRatingCriteriaId().equals(criteriaId)) {
		userRating = userRatingIter;
	    }
	}
	String userRatingStr = userRating == null ? "" : numberFormat.format(userRating.getRating());
	criteriaDto.setUserRating(userRatingStr);

	// check if there is any data returned from DB regarding this item and criteria
	Object[] itemStatistics = null;
	for (Object[] itemStatisticsIter : itemsStatistics) {
	    Long itemIdIter = (Long) itemStatisticsIter[0];
	    Long ratingCriteriaIdIter = (Long) itemStatisticsIter[1];

	    if (itemIdIter.equals(itemId) && ratingCriteriaIdIter.equals(criteriaId)) {
		itemStatistics = itemStatisticsIter;
	    }
	}

	if (itemStatistics != null) {
	    Number averageRating = (Number) itemStatistics[2];
	    criteriaDto.setAverageRating(numberFormat.format(averageRating));
	    criteriaDto.setAverageRatingAsNumber(averageRating);
	    criteriaDto.setNumberOfVotes(String.valueOf(itemStatistics[3]));
	} else {
	    criteriaDto.setAverageRating("0");
	    criteriaDto.setAverageRatingAsNumber(0);
	    criteriaDto.setNumberOfVotes("0");
	}

	criteriaDtos.add(criteriaDto);

    }

}

return itemDtos;
   }
 
Example 16
Source File: CompareAseFiles.java    From systemsgenetics with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param args the command line arguments
 */
@SuppressWarnings("ManualArrayToCollectionCopy")
public static void main(String[] args) throws Exception {
       
	BufferedReader aseReader = new BufferedReader(new FileReader("D:\\ASEcheck\\geuvadis_maskAll4_r20_a10_p2_s1_rq17_m1_gatkGenoGq30\\ase_bh.txt"));
       BufferedReader aseReader2 = new BufferedReader(new FileReader("D:\\ASEcheck\\all_maskAll4_r20_a10_p2_s5_rq17_m1_gatkGenoGq30\\ase_bh.txt"));
       
       HashMap<String, AseVariantBean> aseEffects = new HashMap<String, AseVariantBean>();
       HashSet<String> totalEffects = new HashSet<String>();

       String line;
       String[] elements;
       //Header
       aseReader.readLine();
	while ((line = aseReader.readLine()) != null) {
           elements = TAB_PATTERN.split(line);
		aseEffects.put(elements[7],new AseVariantBean(elements));
	}
       aseReader.close();
       
       
	int aseTotalInFile2 = 0;
	int asePresentInBoth = 0;
	int sameDirection = 0;
	int oppositeDirection = 0;

	aseReader2.readLine();//header
	line = null;
	elements = null;
	while ((line = aseReader2.readLine()) != null) {
           ++aseTotalInFile2;
		elements = TAB_PATTERN.split(line);	
           AseVariantBean currentEffect = new AseVariantBean(elements);
           totalEffects.add(currentEffect.getId().toString());
           
           if(aseEffects.containsKey(currentEffect.getId().toString())){
               AseVariantBean otherEffect =  aseEffects.get(currentEffect.getId().toString());
               asePresentInBoth++;
               if(otherEffect.getEffect()<0.5 && currentEffect.getEffect()<0.5){
                   sameDirection++;
               } else if(otherEffect.getEffect()>0.5 && currentEffect.getEffect()>0.5){
                   sameDirection++;
               } else {
                   oppositeDirection++;
               }
           }
	}
       totalEffects.addAll(aseEffects.keySet());
       aseReader2.close();
       
	NumberFormat numberFormat = NumberFormat.getInstance();
	numberFormat.setMinimumFractionDigits(2);
	numberFormat.setMaximumFractionDigits(2);
	System.out.println("Ase effects in file 1: " + aseEffects.size());
       System.out.println("Ase effects in file 2: " + aseTotalInFile2);
       System.out.println("Total unique Ase effects observed : " + totalEffects.size());
	System.out.println("Ase effects identified in both analyses: " + asePresentInBoth + " (" + numberFormat.format(asePresentInBoth / (double) totalEffects.size()) + ")");
	System.out.println(" - Same direction: " + sameDirection + " (" + numberFormat.format(sameDirection / (double) asePresentInBoth) + ")");
	System.out.println(" - Opposite direction: " + oppositeDirection + " (" + numberFormat.format(oppositeDirection / (double) asePresentInBoth) + ")");

}
 
Example 17
Source File: AbstractFormat.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create a default number format.  The default number format is based on
 * {@link NumberFormat#getNumberInstance(java.util.Locale)} with the only
 * customizing is the maximum number of BigFraction digits, which is set to 0.
 * @param locale the specific locale used by the format.
 * @return the default number format specific to the given locale.
 */
protected static NumberFormat getDefaultNumberFormat(final Locale locale) {
    final NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setMaximumFractionDigits(0);
    nf.setParseIntegerOnly(true);
    return nf;
}
 
Example 18
Source File: AbstractFormat.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create a default number format.  The default number format is based on
 * {@link NumberFormat#getNumberInstance(java.util.Locale)} with the only
 * customizing is the maximum number of BigFraction digits, which is set to 0.  
 * @param locale the specific locale used by the format.
 * @return the default number format specific to the given locale.
 */
protected static NumberFormat getDefaultNumberFormat(final Locale locale) {
    final NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setMaximumFractionDigits(0);
    nf.setParseIntegerOnly(true);
    return nf;
}
 
Example 19
Source File: AbstractFormat.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create a default number format.  The default number format is based on
 * {@link NumberFormat#getNumberInstance(java.util.Locale)} with the only
 * customizing is the maximum number of BigFraction digits, which is set to 0.
 * @param locale the specific locale used by the format.
 * @return the default number format specific to the given locale.
 */
protected static NumberFormat getDefaultNumberFormat(final Locale locale) {
    final NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setMaximumFractionDigits(0);
    nf.setParseIntegerOnly(true);
    return nf;
}
 
Example 20
Source File: CompositeFormat.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Create a default number format.  The default number format is based on
 * {@link NumberFormat#getInstance(java.util.Locale)} with the only
 * customizing that the maximum number of fraction digits is set to 2.
 * @param locale the specific locale used by the format.
 * @return the default number format specific to the given locale.
 */
protected static NumberFormat getDefaultNumberFormat(final Locale locale) {
    final NumberFormat nf = NumberFormat.getInstance(locale);
    nf.setMaximumFractionDigits(2);
    return nf;
}