java.text.DecimalFormat Java Examples

The following examples show how to use java.text.DecimalFormat. 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: AbstractInference.java    From ASTRAL with Apache License 2.0 6 votes vote down vote up
public AbstractInference(Options options, List<Tree> trees,
		List<Tree> extraTrees, List<Tree> toRemoveExtraTrees) {
	super();
	this.options = options;
	this.trees = trees;
	this.extraTrees = extraTrees;
	this.removeExtraTree = options.isRemoveExtraTree();
	this.toRemoveExtraTrees = toRemoveExtraTrees;
	
	df = new DecimalFormat();
	df.setMaximumFractionDigits(2);
	DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
	dfs.setDecimalSeparator('.');
	df.setDecimalFormatSymbols(dfs);

}
 
Example #2
Source File: FIXMatrixUtil.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Calculates the checksum of FIX message. "
        +"Msg - the message for which checksum needs to be calculated;<br>"
        +"Delimiter - the separator of the message fields;<br>"
        +"Example: <br> "
        +"For this message '8=FIX.4.4|9=122|35=D|34=215|49=CLIENT12|52=20100225-19:41:57.316|56=B|1=Marcel|11=13346|21=1|40=2|44=5|54=1|59=0|60=20100225-19:39:52.020|' <br> "
        +"exec calculateChecksum(msg,'|') return checksum is 072"
)
@UtilityMethod
public String calculateChecksum(String msg, char delimiter) {
    char[] chars = msg.replace(delimiter, '\001').toCharArray();
    int checksum = 0;
    for (char c:chars){
        checksum+=c;
    }

    DecimalFormat formatter = new DecimalFormat("000");

    return formatter.format(checksum & 0xFF);
}
 
Example #3
Source File: NumberFormatProviderImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example #4
Source File: Util.java    From DMusic with Apache License 2.0 6 votes vote down vote up
/**
 * 返回数据大小(byte)对应文本
 */
public static String formatSize(long size) {
    DecimalFormat format = new DecimalFormat("####.00");
    if (size < 1024) {
        return size + "bytes";
    } else if (size < 1024 * 1024) {
        float kb = size / 1024f;
        return format.format(kb) + "KB";
    } else if (size < 1024 * 1024 * 1024) {
        float mb = size / (1024 * 1024f);
        return format.format(mb) + "MB";
    } else {
        float gb = size / (1024 * 1024 * 1024f);
        return format.format(gb) + "GB";
    }
}
 
Example #5
Source File: RowGeneratorMeta.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public void setDefault() {
  int i, nrfields = 0;

  allocate( nrfields );

  DecimalFormat decimalFormat = new DecimalFormat();

  for ( i = 0; i < nrfields; i++ ) {
    fieldName[i] = "field" + i;
    fieldType[i] = "Number";
    fieldFormat[i] = "\u00A40,000,000.00;\u00A4-0,000,000.00";
    fieldLength[i] = 9;
    fieldPrecision[i] = 2;
    currency[i] = decimalFormat.getDecimalFormatSymbols().getCurrencySymbol();
    decimal[i] = new String( new char[] { decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() } );
    group[i] = new String( new char[] { decimalFormat.getDecimalFormatSymbols().getGroupingSeparator() } );
    value[i] = "-";
    setEmptyString[i] = false;
  }

  rowLimit = "10";
  neverEnding = false;
  intervalInMs = "5000";
  rowTimeField = "now";
  lastTimeField = "FiveSecondsAgo";
}
 
Example #6
Source File: RelativeDateFormat.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param baseMillis  the time zone (<code>null</code> not permitted).
 */
public RelativeDateFormat(long baseMillis) {
    super();
    this.baseMillis = baseMillis;
    this.showZeroDays = false;
    this.showZeroHours = true;
    this.positivePrefix = "";
    this.dayFormatter = NumberFormat.getNumberInstance();
    this.daySuffix = "d";
    this.hourFormatter = NumberFormat.getNumberInstance();
    this.hourSuffix = "h";
    this.minuteFormatter = NumberFormat.getNumberInstance();
    this.minuteSuffix = "m";
    this.secondFormatter = NumberFormat.getNumberInstance();
    this.secondFormatter.setMaximumFractionDigits(3);
    this.secondFormatter.setMinimumFractionDigits(3);
    this.secondSuffix = "s";

    // we don't use the calendar or numberFormat fields, but equals(Object)
    // is failing without them being non-null
    this.calendar = new GregorianCalendar();
    this.numberFormat = new DecimalFormat("0");
}
 
Example #7
Source File: ManualInputActivity.java    From polling-station-app with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a @link{DocumentData} object of the input date in the same way as the OCR scanner does.
 * @return data - A DocumentData object of the required document data for BAC.
 */
public DocumentData getData() {
    DocumentData data = new DocumentData();
    DecimalFormat formatter = new DecimalFormat("00");
    data.setDocumentNumber(docNumber.getText().toString().toUpperCase());
    data.setDateOfBirth(dobYearSpinner.getSelectedItem().toString().substring(2) +
            formatter.format(dobMonthSpinner.getSelectedItemId()+1) +
            formatter.format(Integer.parseInt(dobDaySpinner.getSelectedItem().toString())));
    data.setExpiryDate(expiryYearSpinner.getSelectedItem().toString().substring(2) +
            formatter.format(expiryMonthSpinner.getSelectedItemId()+1) +
            formatter.format(Integer.parseInt(expiryDaySpinner.getSelectedItem().toString())));
    return data;
}
 
Example #8
Source File: TestgetPatternSeparator_ja.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
    DecimalFormat df = (DecimalFormat)NumberFormat.getInstance(Locale.JAPAN);
    DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
    if (dfs.getPatternSeparator() != ';') {
        throw new Exception("DecimalFormatSymbols.getPatternSeparator doesn't return ';' in ja locale");
    }
}
 
Example #9
Source File: LocaleSafeDecimalFormat.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Regardless of the default locale, comma ('.') is used as decimal separator
 *
 * @param source
 * @return
 * @throws ParseException
 */
public BigDecimal parse(String source) throws ParseException {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#.#", symbols);
    format.setParseBigDecimal(true);
    return (BigDecimal) format.parse(source);
}
 
Example #10
Source File: DownloadHelper.java    From NightWidget with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method helps to process the last sgv value received. It also raise
 * alarms if needed.
 * 
 * @param sgv
 *            , last sgv value
 * @param views
 *            , access to the Widget UI.
 */
private String processMBGValue(String mbg, RemoteViews views) {
	log.debug( "processMBGValue " + mbg +" METRICS "+prefs.getString("metric_preference_widget", "1"));
	Float mbgInt = -1f;
	float divisor = 1;
	DecimalFormat df = new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.US));
	if (prefs.getString("metric_preference_widget", "1").equals("2")){
		divisor = 18;
	}
	try {

		mbgInt =  Float.parseFloat(mbg);
		if (prefs.getString("metric_preference_widget", "1").equals("2"))
			mbgInt = (float) mbgInt / divisor;

	} catch (Exception e) {
		log.error( "error",e);
	}
	log.debug( "processMBGValueINT " + mbgInt);
	if (mbgInt <= 0) {
		views.setTextColor(R.id.mbg_label, Color.WHITE);
		views.setTextColor(R.id.mbg_time_id, Color.WHITE);
		views.setTextColor(R.id.mbg_value, Color.WHITE);
		return mbg;
	} else {
		views.setTextColor(R.id.mbg_label, Color.WHITE);
		views.setTextColor(R.id.mbg_time_id, Color.WHITE);
		views.setTextColor(R.id.mbg_value, Color.WHITE);
	}
	if (prefs.getString("metric_preference_widget", "1").equals("2"))
		return df.format(mbgInt);
	else
		return "" + (mbgInt.intValue());
}
 
Example #11
Source File: OdsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static String formatNumberAsDecimal( Object data )
{
	Number number=(Number)data;
	DecimalFormat numberFormat = new DecimalFormat( "0.##############" );
	numberFormat.setMaximumFractionDigits( 15 );
	updateDecimalSeparator( numberFormat );
	return numberFormat.format( number );
}
 
Example #12
Source File: StandardCategoryToolTipGeneratorTests.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A test for bug 1481087.
 */
public void testEquals1481087() {
    StandardCategoryToolTipGenerator g1
            = new StandardCategoryToolTipGenerator("{0}",
            new DecimalFormat("0.00"));
    StandardCategoryItemLabelGenerator g2
            = new StandardCategoryItemLabelGenerator("{0}",
            new DecimalFormat("0.00"));
    assertFalse(g1.equals(g2));
}
 
Example #13
Source File: X8PieView.java    From FimiX8-RE with MIT License 5 votes vote down vote up
private void drawPieValue(Canvas canvas, String name, float startX, float startY, float percent) {
    this.dataPaint.getTextBounds(name, 0, name.length(), this.dataTextBound);
    canvas.drawText(name, startX - ((float) (this.dataTextBound.width() / 2)), (((float) (this.dataTextBound.height() / 2)) + startY) - 20.0f, this.dataPaint);
    String percentString = new DecimalFormat("0.0").format((double) (100.0f * percent)) + "%";
    this.dataPaint.getTextBounds(percentString, 0, percentString.length(), this.dataTextBound);
    canvas.drawText(percentString, startX - ((float) (this.dataTextBound.width() / 2)), (((float) (this.dataTextBound.height() / 2)) + startY) + 30.0f, this.dataPaint);
}
 
Example #14
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_setNegativePrefix() throws Exception {
    DecimalFormat format = new DecimalFormat();
    assertEquals("-", format.getNegativePrefix());

    format.setNegativePrefix("NegPrf");
    assertEquals("NegPrf", format.getNegativePrefix());
    assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45);
    format.setNegativePrefix("");
    assertEquals("", format.getNegativePrefix());

    format.setNegativePrefix(null);
    assertNull(format.getNegativePrefix());
}
 
Example #15
Source File: TimeCountDownView.java    From ClockView with Apache License 2.0 5 votes vote down vote up
public TimeCountDownView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    View view = inflate(context, R.layout.timedown,this);
    hour_text= (TextView) view.findViewById(R.id.hour_text);
    minute_text= (TextView) view.findViewById(R.id.minute_text);
    seconds_text= (TextView) view.findViewById(R.id.seconds_text);
    df =new DecimalFormat("00");

}
 
Example #16
Source File: Commodity.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public Commodity(String exchangeSymbol, Exchange exchange, DecimalFormat decimalFormat, BigDecimal minimumTickSize, BigDecimal contractMultiplier, String currency) {
    this.exchangeSymbol = exchangeSymbol;
    this.exchange = exchange;
    this.decimalFormat = decimalFormat;
    this.minimumTickSize = minimumTickSize;
    this.contractMultiplier = contractMultiplier;
    this.currency = currency;
}
 
Example #17
Source File: RingOfAccuracy.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
public String statsInfo() {
	if (isIdentified()){
		return Messages.get(this, "stats", new DecimalFormat("#.##").format(100f * (Math.pow(1.3f, soloBonus()) - 1f)));
	} else {
		return Messages.get(this, "typical_stats", new DecimalFormat("#.##").format(30f));
	}
}
 
Example #18
Source File: MaterialsList.java    From Ic2ExpReactorPlanner with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder result = new StringBuilder(1000);
    DecimalFormat materialDecimalFormat = new DecimalFormat(getI18n("UI.MaterialDecimalFormat"));
    for (Map.Entry<String, Double> entrySet : materials.entrySet()) {
        double count = entrySet.getValue();
        String formattedNumber = materialDecimalFormat.format(count);
        result.append(String.format("%s %s\n", formattedNumber, entrySet.getKey())); //NOI18N
    }
    return result.toString();
}
 
Example #19
Source File: BtcFormat.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/** Sets the number of fractional decimal places to be displayed on the given
 *  NumberFormat object to the value of the given integer.
 *  @return The minimum and maximum fractional places settings that the
 *          formatter had before this change, as an ImmutableList. */
private static ImmutableList<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) {
    ImmutableList<Integer> ante = ImmutableList.of(
        formatter.getMinimumFractionDigits(),
        formatter.getMaximumFractionDigits()
    );
    formatter.setMinimumFractionDigits(min);
    formatter.setMaximumFractionDigits(max);
    return ante;
}
 
Example #20
Source File: DebugDialogController.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String getMemoryTableValue(int rowIndex, int columnIndex)
{
	final long MEGABYTE = 1024 * 1024;

	MemoryUsage usage;
	if (rowIndex == 0)
	{
		usage = MEMORY_BEAN.getHeapMemoryUsage();
	}
	else
	{
		usage = MEMORY_BEAN.getNonHeapMemoryUsage();
	}
	final NumberFormat format = new DecimalFormat("###,###,###");
	switch (columnIndex)
	{
		case 0:
			return (rowIndex == 0) ? "Heap" : "Non-Heap";
		case 1:
			return format.format(usage.getInit() / MEGABYTE);
		case 2:
			return format.format(usage.getUsed() / MEGABYTE);
		case 3:
			return format.format(usage.getCommitted() / MEGABYTE);
		case 4:
			return format.format(usage.getMax() / MEGABYTE);
		case 5:
			return String.valueOf(100 * (usage.getUsed() / usage.getMax()));
		default:
			throw new IllegalStateException("Unexpected column index: " + columnIndex);
	}
}
 
Example #21
Source File: DataTypes.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public static boolean isDecimal(String input) {
  try {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    String pattern = "#,##0.0#";
    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
    BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse(input);
    return true;
  } catch (Exception ex) {
    return false;
  }
}
 
Example #22
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_parse_minusInfinityBigDecimalFalse() {
    // Regression test for HARMONY-106
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    Number number = format.parse("-" + symbols.getInfinity(),
            new ParsePosition(0));
    assertTrue(number instanceof Double);
    assertTrue(Double.isInfinite(number.doubleValue()));
}
 
Example #23
Source File: DataFormatter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public InternalDecimalFormatWithScale(String pattern, DecimalFormatSymbols symbols) {
    df = new DecimalFormat(trimTrailingCommas(pattern), symbols);
    setExcelStyleRoundingMode(df);
    Matcher endsWithCommasMatcher = endsWithCommas.matcher(pattern);
    if (endsWithCommasMatcher.find()) {
        String commas = (endsWithCommasMatcher.group(1));
        BigDecimal temp = BigDecimal.ONE;
        for (int i = 0; i < commas.length(); ++i) {
            temp = temp.multiply(ONE_THOUSAND);
        }
        divider = temp;
    } else {
        divider = null;
    }
}
 
Example #24
Source File: Bin.java    From streaminer with Apache License 2.0 5 votes vote down vote up
public JSONArray toJSON(DecimalFormat format) {
  JSONArray binJSON = new JSONArray();
  binJSON.add(NumberUtil.roundNumber(_mean, format));
  binJSON.add(NumberUtil.roundNumber(_count, format));
  _target.addJSON(binJSON, format);
  return binJSON;
}
 
Example #25
Source File: Creature.java    From dctb-utfpr-2018-1 with Apache License 2.0 5 votes vote down vote up
public double constantMultiplier() {
    double max=1.66, min=1.1;
    double random = min + Math.random() * (max - min);
    DecimalFormat decimal = new DecimalFormat("#.##");
    String rS = decimal.format(random);
    return(Double.parseDouble(rS.replace(",", ".")));
}
 
Example #26
Source File: QueueCLI.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void printQueueInfo(PrintWriter writer, QueueInfo queueInfo) {
  writer.print("Queue Name : ");
  writer.println(queueInfo.getQueueName());

  writer.print("\tState : ");
  writer.println(queueInfo.getQueueState());
  DecimalFormat df = new DecimalFormat("#.0");
  writer.print("\tCapacity : ");
  writer.println(df.format(queueInfo.getCapacity() * 100) + "%");
  writer.print("\tCurrent Capacity : ");
  writer.println(df.format(queueInfo.getCurrentCapacity() * 100) + "%");
  writer.print("\tMaximum Capacity : ");
  writer.println(df.format(queueInfo.getMaximumCapacity() * 100) + "%");
  writer.print("\tDefault Node Label expression : ");
  if (null != queueInfo.getDefaultNodeLabelExpression()) {
    writer.println(queueInfo.getDefaultNodeLabelExpression());
  } else {
    writer.println();
  }

  Set<String> nodeLabels = queueInfo.getAccessibleNodeLabels();
  StringBuilder labelList = new StringBuilder();
  writer.print("\tAccessible Node Labels : ");
  for (String nodeLabel : nodeLabels) {
    if (labelList.length() > 0) {
      labelList.append(',');
    }
    labelList.append(nodeLabel);
  }
  writer.println(labelList.toString());
}
 
Example #27
Source File: ExportingDialog.java    From apkextractor with GNU General Public License v3.0 5 votes vote down vote up
public void setProgressOfWriteBytes(long current,long total){
    if(current<0)return;
    if(current>total)return;
    progressBar.setMax((int)(total/1024));
    progressBar.setProgress((int)(current/1024));
    DecimalFormat dm=new DecimalFormat("#.00");
    int percent=(int)(Double.valueOf(dm.format((double)current/total))*100);
    att_right.setText(Formatter.formatFileSize(getContext(),current)+"/"+Formatter.formatFileSize(getContext(),total)+"("+percent+"%)");
}
 
Example #28
Source File: StandardCategoryToolTipGeneratorTests.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A test for bug 1481087.
 */
public void testEquals1481087() {
    StandardCategoryToolTipGenerator g1 
        = new StandardCategoryToolTipGenerator("{0}", 
                new DecimalFormat("0.00"));
    StandardCategoryItemLabelGenerator g2 
        = new StandardCategoryItemLabelGenerator("{0}", 
                new DecimalFormat("0.00"));
    assertFalse(g1.equals(g2));
}
 
Example #29
Source File: NumericToCharFunctions.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public void setup() {
    buffer = buffer.reallocIfNeeded(100);
    byte[] buf = new byte[right.end - right.start];
    right.buffer.getBytes(right.start, buf, 0, right.end - right.start);
    String inputFormat = new String(buf);
    outputFormat = new java.text.DecimalFormat(inputFormat);
}
 
Example #30
Source File: TieRoundingTest.java    From openjdk-jdk9 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);
    }
}