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

The following examples show how to use java.text.NumberFormat#setGroupingUsed() . 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: CSVUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
private static ByteBuffer encodeLogicalType(final Field field, final String fieldValue) {
    String logicalType = field.getProp("logicalType");
    if (!"decimal".contentEquals(logicalType)) {
        throw new IllegalArgumentException("The field '" + field.name() + "' has a logical type of '" + logicalType
                + "' that is currently not supported.");
    }

    JsonNode rawPrecision = field.getJsonProp("precision");
    if (null == rawPrecision) {
        throw new IllegalArgumentException("The field '" + field.name() + "' is missing the required precision property");
    }
    int precision = rawPrecision.asInt();
    JsonNode rawScale = field.getJsonProp("scale");
    int scale = null == rawScale ? 0 : rawScale.asInt();

    NumberFormat numberFormat = DecimalFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    normalizeNumberFormat(numberFormat, scale, precision);
    BigDecimal decimal = null == fieldValue ? new BigDecimal(retrieveDefaultFieldValue(field).asText()) : new BigDecimal(fieldValue);
    return ByteBuffer.wrap(numberFormat.format(decimal).getBytes(StandardCharsets.UTF_8));
}
 
Example 2
Source File: StopWatch.java    From neural with MIT License 6 votes vote down vote up
/**
 * Return a string with a table describing all tasks performed.
 * For custom reporting, call getTaskInfo() and use the task info directly.
 */
public String prettyPrint() {
    StringBuilder sb = new StringBuilder(shortSummary());
    sb.append('\n');
    if (!this.keepTaskList) {
        sb.append("No task info kept");
    } else {
        sb.append("-----------------------------------------\n");
        sb.append("ms     %     Task name\n");
        sb.append("-----------------------------------------\n");
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMinimumIntegerDigits(5);
        nf.setGroupingUsed(false);
        NumberFormat pf = NumberFormat.getPercentInstance();
        pf.setMinimumIntegerDigits(3);
        pf.setGroupingUsed(false);
        for (TaskInfo task : getTaskInfo()) {
            sb.append(nf.format(task.getTimeMillis())).append("  ");
            sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append("  ");
            sb.append(task.getTaskName()).append("\n");
        }
    }
    return sb.toString();
}
 
Example 3
Source File: NumberConverter.java    From Oceanus with Apache License 2.0 6 votes vote down vote up
/**
 * Convert an input Number object into a String.
 *
 * @param value The input value to be converted
 * @return the converted String value.
 * @throws Throwable if an error occurs converting to a String
 */
@Override
protected String convertToString(Object value) throws Throwable {

    String result = null;
    if (useLocaleFormat && value instanceof Number) {
        NumberFormat format = getFormat();
        format.setGroupingUsed(false);
        result = format.format(value);
        if (log().isDebugEnabled()) {
            log().debug("    Converted  to String using format '" + result + "'");
        }

    } else {
        result = value.toString();
        if (log().isDebugEnabled()) {
            log().debug("    Converted  to String using toString() '" + result + "'");
        }
    }
    return result;

}
 
Example 4
Source File: NativeNumber.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.7.4.5 Number.prototype.toFixed (fractionDigits) specialized for int fractionDigits
 *
 * @param self           self reference
 * @param fractionDigits how many digits should be after the decimal point, 0 if undefined
 *
 * @return number in decimal fixed point notation
 */
@SpecializedFunction
public static String toFixed(final Object self, final int fractionDigits) {
    if (fractionDigits < 0 || fractionDigits > 20) {
        throw rangeError("invalid.fraction.digits", "toFixed");
    }

    final double x = getNumberValue(self);
    if (Double.isNaN(x)) {
        return "NaN";
    }

    if (Math.abs(x) >= 1e21) {
        return JSType.toString(x);
    }

    final NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
    format.setMinimumFractionDigits(fractionDigits);
    format.setMaximumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);
    format.setRoundingMode(RoundingMode.HALF_UP);

    return format.format(x);
}
 
Example 5
Source File: MathUtil.java    From nbp with Apache License 2.0 6 votes vote down vote up
/**
 * Rounding formatting numbers
 * Optional point form, default 2 bit precision
 * @param val The value that needs to be converted
 * @param isGroupingUsed Whether to display points
 * @param precision The first is the maximum number of decimal places,
 *                  and the second is the minimum number of decimal places.
 * @return String
 */
public static String parseNumber(Object val, Boolean isGroupingUsed,
        int... precision)
{
    int max = PRECISION_TWO;
    int min = PRECISION_TWO;
    if (precision.length == PRECISION_ONE)
    {
        max = precision[0];
    }
    else if (precision.length == PRECISION_TWO)
    {
        max = precision[0];
        min = precision[1];
    }
    NumberFormat nf = NumberFormat.getNumberInstance();

    nf.setRoundingMode(RoundingMode.HALF_UP);
    nf.setMaximumFractionDigits(max);
    nf.setMinimumFractionDigits(min > max ? max : min);
    nf.setGroupingUsed(isGroupingUsed);
    return nf.format(val);
}
 
Example 6
Source File: StopWatch.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Return a string with a table describing all tasks performed.
 * For custom reporting, call getTaskInfo() and use the task info directly.
 */
public String prettyPrint() {
    StringBuilder sb = new StringBuilder(shortSummary());
    sb.append('\n');
    if (!this.keepTaskList) {
        sb.append("No task info kept");
    } else {
        TaskInfo[] tasks = getTaskInfo();
        sb.append("-----------------------------------------\n");
        sb.append("ms     %     Task name\n");
        sb.append("-----------------------------------------\n");
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMinimumIntegerDigits(5);
        nf.setGroupingUsed(false);
        NumberFormat pf = NumberFormat.getPercentInstance();
        pf.setMinimumIntegerDigits(3);
        pf.setGroupingUsed(false);
        for (TaskInfo task : tasks) {
            sb.append(nf.format(task.getTimeMillis())).append("  ");
            sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append("  ");
            sb.append(task.getTaskName()).append("\n");
        }
    }
    return sb.toString();
}
 
Example 7
Source File: ReservationId.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public NumberFormat initialValue() {
  NumberFormat fmt = NumberFormat.getInstance();
  fmt.setGroupingUsed(false);
  fmt.setMinimumIntegerDigits(4);
  return fmt;
}
 
Example 8
Source File: Task.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
@Override
public NumberFormat initialValue() {
  NumberFormat fmt = NumberFormat.getInstance();
  fmt.setGroupingUsed(false);
  fmt.setMinimumIntegerDigits(6);
  return fmt;
}
 
Example 9
Source File: StoreUtils.java    From qmq with Apache License 2.0 5 votes vote down vote up
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 10
Source File: UtilAll.java    From RocketMQ-Master-analyze 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 11
Source File: MuleRemoteDebuggerConfPanel.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
private void createUIComponents() {
    NumberFormat format = NumberFormat.getInstance();
    format.setGroupingUsed(false);
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMaximum(65535);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);
    portTextField = new JFormattedTextField(formatter);
    jvmPortTextField = new JFormattedTextField(formatter);

    appsMap = new JBTable(new ModulesTableModel());

}
 
Example 12
Source File: SystemProcessImpl.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * @return a unique number which shorts in descending order
 */
private static String nextId() {
  NumberFormat numberFormat = NumberFormat.getInstance();
  numberFormat.setMinimumIntegerDigits(10);
  numberFormat.setGroupingUsed(false);
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
  return Utils.format("{}-{}", dateFormat.format(new Date()), numberFormat.format(fileCounter.incrementAndGet()));
}
 
Example 13
Source File: StatsFormatter.java    From JPPF with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the formatter for double values.
 * @return a {@code NumberFormat} instance.
 */
private NumberFormat initDoubleFormatter() {
  final NumberFormat doubleFormatter = NumberFormat.getInstance(locale);
  doubleFormatter.setGroupingUsed(true);
  doubleFormatter.setMinimumFractionDigits(2);
  doubleFormatter.setMaximumFractionDigits(2);
  doubleFormatter.setMinimumIntegerDigits(1);
  return doubleFormatter;
}
 
Example 14
Source File: DoubleFormatTest.java    From swage with Apache License 2.0 5 votes vote down vote up
/**
 * This test runs a comparision of the performance of various string
 * formatting methods and validates that DoubleFormat is the fastest.
 * Not a replacement for in-depth analysis.
 *
 * If this test is failing, either DoubleFormat has a performance
 * regression or the built-in methods have improved enough to reconsider.
 *
 * The test can take multiple seconds to run.
 */
@Test
public void benchmark() throws Exception {
    final long iterations = 1000000;

    long duration_StringFormat = run_benchmark(iterations, (a) -> String.format("%.6f", a));

    NumberFormat javaFormatter = NumberFormat.getInstance();
    javaFormatter.setMinimumFractionDigits(0);
    javaFormatter.setMaximumFractionDigits(6);
    javaFormatter.setGroupingUsed(false);
    long duration_JavaFormat = run_benchmark(iterations, (a) -> javaFormatter.format(a));

    long duration_JavaStringBuilder = run_benchmark(iterations, (a) -> (new StringBuilder()).append(a));

    long duration_DoubleFormat = run_benchmark(iterations, (a) -> DoubleFormat.format(new StringBuilder(), a));

    System.out.println("DoubleFormat Performance comparison: " + iterations +" iterations");
    System.out.println("\tJava String.format: " + duration_StringFormat + " ms");
    System.out.println("\tJava NumberFormat:  " + duration_JavaFormat + " ms");
    System.out.println("\tJava StringBuilder: " + duration_JavaStringBuilder + " ms");
    System.out.println("\tDoubleFormat:       " + duration_DoubleFormat + " ms");

    assertTrue(duration_DoubleFormat < duration_StringFormat);
    assertTrue(duration_DoubleFormat < duration_JavaFormat);
    assertTrue(duration_DoubleFormat < duration_JavaStringBuilder);
}
 
Example 15
Source File: TestNumberFormat.java    From tez with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testLongWithPadding() throws Exception {
  FastNumberFormat fastNumberFormat = FastNumberFormat.getInstance();
  fastNumberFormat.setMinimumIntegerDigits(6);
  NumberFormat numberFormat = NumberFormat.getInstance();
  numberFormat.setGroupingUsed(false);
  numberFormat.setMinimumIntegerDigits(6);
  long[] testLongs = {1, 23, 456, 7890, 12345, 678901, 2345689, 0, -0, -1, -23, -456, -7890, -12345, -678901, -2345689};
  for (long l: testLongs) {
    Assert.assertEquals("Number formats should be equal", numberFormat.format(l), fastNumberFormat.format(l));
  }
}
 
Example 16
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 17
Source File: DisplayFormatters.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
/**
  * Format a real number
  *
  * @param value real number to format
  * @param precision max # of digits after the decimal place
  * @param bTruncateZeros remove any trailing zeros after decimal place
  * @param bRound Whether the number will be rounded to the precision, or
  *                truncated off.
  * @return formatted string
  */
public static String
formatDecimal(
		double value,
		int precision,
		boolean bTruncateZeros,
		boolean bRound)
{
	if (Double.isNaN(value) || Double.isInfinite(value)) {
		return Constants.INFINITY_STRING;
	}

	double tValue;
	if (bRound) {
		tValue = value;
	} else {
		// NumberFormat rounds, so truncate at precision
		if (precision == 0) {
			tValue = (long) value;
		} else {
			double shift = Math.pow(10, precision);
			tValue = ((long) (value * shift)) / shift;
		}
	}

	int cache_index = (precision << 2) + ((bTruncateZeros ? 1 : 0) << 1)
			+ (bRound ? 1 : 0);

	NumberFormat nf = null;

	if (cache_index < cached_number_formats.length) {
		nf = cached_number_formats[cache_index];
	}

	if (nf == null) {
		nf = NumberFormat.getNumberInstance();
		nf.setGroupingUsed(false); // no commas
		if (!bTruncateZeros) {
			nf.setMinimumFractionDigits(precision);
		}
		if (bRound) {
			nf.setMaximumFractionDigits(precision);
		}

		if (cache_index < cached_number_formats.length) {
			cached_number_formats[cache_index] = nf;
		}
	}

	return nf.format(tValue);
}
 
Example 18
Source File: StateGraph.java    From iBioSim with Apache License 2.0 4 votes vote down vote up
public void outputStateGraph(String file, boolean withProbs) {
	try {
		NumberFormat num = NumberFormat.getInstance();
		num.setMaximumFractionDigits(6);
		num.setGroupingUsed(false);
		BufferedWriter out = new BufferedWriter(new FileWriter(file));
		out.write("digraph G {\n");
		for (State m : stateGraph) {
			// for (String state : stateGraph.keySet()) {
			// for (State m : stateGraph.get(state)) {
			if (withProbs) {
				out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + m.stateVector
						+ ">\\nProb = " + num.format(m.getCurrentProb()) + "\"]\n");
			}
			else {
				out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + m.stateVector
						+ ">\"]\n");
			}
			for (StateTransitionPair next : m.getNextStatesWithTrans()) {
				/*
				 * System.out.println(m.getID() + " -> " +
				 * next.getState().getID() + " [label=\"" +
				 * next.getTransition() + "\\n");
				 * System.out.println(m.getTransitionSum());
				 * System.out.println(lhpn.getTransitionRateTree(
				 * next.getTransition ()).evaluateExpr(m.getVariables()));
				 */
				if (next.isEnabled()) {
					out.write(m.getID() + " -> " + next.getState().getID() + " [label=\""
							+ next.getTransitionName() + "\\n" + num.format(next.getTransition()) + "\"]\n");
				}
				// if (lhpn.getTransitionRateTree(next.getTransition())
				// != null) {
				// out.write(m.getID()
				// + " -> "
				// + next.getState().getID()
				// + " [label=\""
				// + next.getTransition()
				// + "\\n"
				// +
				// num.format((lhpn.getTransitionRateTree(next.getTransition()).evaluateExpr(m
				// .getVariables()) /*
				// * / m . getTransitionSum ( )
				// */)) + "\"]\n");
				// }
				// else {
				// out.write(m.getID() + " -> " +
				// next.getState().getID() +
				// " [label=\"" + next.getTransition() + "\"]\n");
				// }
			}
		}
		// }
		out.write("}");
		out.close();
	}
	catch (Exception e) {
		e.printStackTrace();
		System.err.println("Error outputting state graph as dot file.");
	}
}
 
Example 19
Source File: NumberFormatter.java    From Strata with Apache License 2.0 3 votes vote down vote up
/**
 * Obtains a formatter for decimal percentages configured by grouping and decimal places.
 * <p>
 * The formatter will have the specified number of decimal places.
 * The integer part will be grouped if the flag is set.
 * The decimal part will never be grouped or truncated.
 * The implementation uses English locale data, which uses commas as a separator and a decimal point (dot).
 * The formatter will suffix the output with '%'.
 * Numbers will be rounded using {@link RoundingMode#HALF_EVEN}
 * <p>
 * The number passed in must be the decimal representation of the percentage.
 * It will be multiplied by 100 before formatting.
 *
 * @param grouped  true to group, false to not group
 * @param minDecimalPlaces  the minimum number of decimal places, from 0 to 9
 * @param maxDecimalPlaces  the minimum number of decimal places, from 0 to 9
 * @return the formatter
 * @throws IllegalArgumentException if the decimal places is invalid
 */
public static NumberFormatter ofPercentage(boolean grouped, int minDecimalPlaces, int maxDecimalPlaces) {
  ArgChecker.inRangeInclusive(minDecimalPlaces, 0, 9, "minDecimalPlaces");
  ArgChecker.inRangeInclusive(maxDecimalPlaces, 0, 9, "maxDecimalPlaces");
  ArgChecker.isTrue(minDecimalPlaces <= maxDecimalPlaces, "Expected minDecimalPlaces <= maxDecimalPlaces");
  NumberFormat format = NumberFormat.getPercentInstance(Locale.ENGLISH);
  format.setGroupingUsed(grouped);
  format.setMinimumIntegerDigits(1);
  format.setMinimumFractionDigits(minDecimalPlaces);
  format.setMaximumFractionDigits(maxDecimalPlaces);
  return new NumberFormatter(format);
}
 
Example 20
Source File: TestSampleIndex.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
     * Create and populate relation in the {@link #namespace}.
     * 
     * @return The #of distinct entries.
     */
    private int loadData(final int scale) {

		final String[] names = new String[] { "John", "Mary", "Saul", "Paul",
				"Leon", "Jane", "Mike", "Mark", "Jill", "Jake", "Alex", "Lucy" };

		final Random rnd = new Random();
		
		// #of distinct instances of each name.
		final int populationSize = Math.max(10, (int) Math.ceil(scale / 10.));
		
		// #of trailing zeros for each name.
		final int nzeros = 1 + (int) Math.ceil(Math.log10(populationSize));
		
//		System.out.println("scale=" + scale + ", populationSize="
//				+ populationSize + ", nzeros=" + nzeros);

		final NumberFormat fmt = NumberFormat.getIntegerInstance();
		fmt.setMinimumIntegerDigits(nzeros);
		fmt.setMaximumIntegerDigits(nzeros);
		fmt.setGroupingUsed(false);
		
        // create the relation.
        final R rel = new R(jnl, namespace, ITx.UNISOLATED, new Properties());
        rel.create();

        // data to insert.
		final E[] a = new E[scale];

		for (int i = 0; i < scale; i++) {

			final String n1 = names[rnd.nextInt(names.length)]
					+ fmt.format(rnd.nextInt(populationSize));

			final String n2 = names[rnd.nextInt(names.length)]
					+ fmt.format(rnd.nextInt(populationSize));

//			System.err.println("i=" + i + ", n1=" + n1 + ", n2=" + n2);
			
			a[i] = new E(n1, n2);
			
        }

		// sort before insert for efficiency.
		Arrays.sort(a,R.primaryKeyOrder.getComparator());
		
        // insert data (the records are not pre-sorted).
        final long ninserts = rel.insert(new ChunkedArrayIterator<E>(a.length, a, null/* keyOrder */));

        // Do commit since not scale-out.
        jnl.commit();

        // should exist as of the last commit point.
        this.rel = (R) jnl.getResourceLocator().locate(namespace,
                ITx.READ_COMMITTED);

        assertNotNull(rel);

        return (int) ninserts;
        
    }