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: Util.java From DMusic with Apache License 2.0 | 6 votes |
/** * 返回数据大小(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 #2
Source File: RelativeDateFormat.java From buffer_bci with GNU General Public License v3.0 | 6 votes |
/** * 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 #3
Source File: AbstractInference.java From ASTRAL with Apache License 2.0 | 6 votes |
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 #4
Source File: RowGeneratorMeta.java From pentaho-kettle with Apache License 2.0 | 6 votes |
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 #5
Source File: NumberFormatProviderImpl.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * 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 #6
Source File: FIXMatrixUtil.java From sailfish-core with Apache License 2.0 | 6 votes |
@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 #7
Source File: Parser.java From morpheus-core with Apache License 2.0 | 5 votes |
/** * Returns a newly created Parser for Double * @param pattern the decimal format pattern * @param multiplier the multiplier to apply * @return newly created Parser */ public static Parser<Double> ofDouble(String pattern, int multiplier) { final DecimalFormat decimalFormat = createDecimalFormat(pattern, multiplier); return new ParserOfDouble(defaultNullCheck, value -> { try { return decimalFormat.parse(value); } catch (Exception ex) { throw new FormatException("Failed to parse value into double: " + value, ex); } }); }
Example #8
Source File: RecognitionPerformanceIT.java From javaanpr with Educational Community License v2.0 | 5 votes |
/** * Goes through all the test images and measures the time it took to recognize them all. * <p> * This is only an information test right now, doesn't fail. * * @throws Exception an Exception */ @Test public void testAllSnapshots() throws Exception { final int measurementCount = 2; final int repetitions = 100; List<Long> timeList = new ArrayList<>(); List<String> plateList = new ArrayList<>(repetitions * (measurementCount + 5) * carSnapshots.size()); for (int i = 0; i < measurementCount + 1; i++) { long start = System.currentTimeMillis(); for (int j = 0; j < repetitions; j++) { for (CarSnapshot snap : carSnapshots) { String plateText = intelligence.recognize(snap); plateList.add(plateText); } } long end = System.currentTimeMillis(); long duration = end - start; if (i != 0) { // first is a warmup run timeList.add(duration); } } DecimalFormat format = new DecimalFormat("#0.00"); logger.info("Images:\t{}\tTime spent:\t{}ms", carSnapshots.size(), format.format(TestUtility.average(timeList))); assertEquals(repetitions * (measurementCount + 1) * carSnapshots.size(), plateList.size()); }
Example #9
Source File: SocketValidateReceive.java From Tomcat8-Source-Read with MIT License | 5 votes |
private static void printStats(long start, double mb, int count, DecimalFormat df, BigDecimal total) { long time = System.currentTimeMillis(); double seconds = ((double)(time-start))/1000; System.out.println("Throughput " + df.format(mb/seconds) + " MB/seconds messages " + count + ", total " + mb + " MB, total " + total + " bytes."); }
Example #10
Source File: SVGWriter.java From jts with GNU Lesser General Public License v2.1 | 5 votes |
/** * Creates the <code>DecimalFormat</code> used to write <code>double</code>s * with a sufficient number of decimal places. * *@param precisionModel the <code>PrecisionModel</code> used to determine * the number of decimal places to write. *@return a <code>DecimalFormat</code> that write <code>double</code> * s without scientific notation. */ private static DecimalFormat createFormatter(PrecisionModel precisionModel) { // the default number of decimal places is 16, which is sufficient // to accomodate the maximum precision of a double. int decimalPlaces = precisionModel.getMaximumSignificantDigits(); // specify decimal separator explicitly to avoid problems in other locales DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); String fmtString = "0" + (decimalPlaces > 0 ? "." : "") + stringOfChar('#', decimalPlaces); return new DecimalFormat(fmtString, symbols); }
Example #11
Source File: GssFunctions.java From closure-stylesheets with Apache License 2.0 | 5 votes |
@Override protected CssNumericNode calculate(List<CssNumericNode> args, ErrorManager errorManager) throws GssFunctionException { if (args.size() == 0) { throw error("Not enough arguments", errorManager, args.get(0).getSourceCodeLocation()); } double total = Double.valueOf(args.get(0).getNumericPart()); String overallUnit = args.get(0).getUnit(); for (CssNumericNode node : args.subList(1, args.size())) { if (node.getUnit() != null && !node.getUnit().equals(CssNumericNode.NO_UNITS)) { throw error( "Only the first argument may have a unit associated with it, " + " but has unit: " + node.getUnit(), errorManager, node.getSourceCodeLocation()); } double value = Double.valueOf(node.getNumericPart()); total = performOperation(total, value); } String resultString = new DecimalFormat(DECIMAL_FORMAT, US_SYMBOLS).format(total); return new CssNumericNode(resultString, overallUnit != null ? overallUnit : CssNumericNode.NO_UNITS, args.get(0).getSourceCodeLocation()); }
Example #12
Source File: StandardTickUnitSource.java From ECG-Viewer with GNU General Public License v2.0 | 5 votes |
/** * Returns a tick unit that is larger than the supplied unit. * * @param unit the unit (<code>null</code> not permitted). * * @return A tick unit that is larger than the supplied unit. */ @Override public TickUnit getLargerTickUnit(TickUnit unit) { double x = unit.getSize(); double log = Math.log(x) / LOG_10_VALUE; double higher = Math.ceil(log); return new NumberTickUnit(Math.pow(10, higher), new DecimalFormat("0.0E0")); }
Example #13
Source File: kNN.java From tsml with GNU General Public License v3.0 | 5 votes |
public static void test1NNvsIB1(boolean norm){ System.out.println("FIRST BASIC SANITY TEST FOR THIS WRAPPER"); System.out.print("Compare 1-NN with IB1, normalisation turned"); String str=norm?" on":" off"; System.out.println(str); System.out.println("Compare on the UCI data sets"); System.out.print("If normalisation is off, then there may be differences"); kNN knn = new kNN(1); IBk ib1=new IBk(1); knn.normalise(norm); int diff=0; DecimalFormat df = new DecimalFormat("####.###"); for(String s:DatasetLists.uciFileNames){ Instances train=DatasetLoading.loadDataNullable("Z:/ArchiveData/Uci_arff/"+s+"/"+s+"-train"); Instances test=DatasetLoading.loadDataNullable("Z:/ArchiveData/Uci_arff/"+s+"/"+s+"-test"); try{ knn.buildClassifier(train); // ib1.buildClassifier(train); ib1.buildClassifier(train); double a1=ClassifierTools.accuracy(test, knn); double a2=ClassifierTools.accuracy(test, ib1); if(a1!=a2){ diff++; System.out.println(s+": 1-NN ="+df.format(a1)+" ib1="+df.format(a2)); } }catch(Exception e){ System.out.println(" Exception builing a classifier"); System.exit(0); } } System.out.println("Total problems ="+DatasetLists.uciFileNames.length+" different on "+diff); }
Example #14
Source File: ByteHexHelper.java From FimiX8-SDFG with MIT License | 5 votes |
public static String currentData() { StringBuffer stringBuffer = new StringBuffer(); DecimalFormat decimalFormat = new DecimalFormat("00"); Calendar calendar = Calendar.getInstance(); String year = decimalFormat.format((long) calendar.get(1)); String month = decimalFormat.format((long) (calendar.get(2) + 1)); String day = decimalFormat.format((long) calendar.get(5)); String hour = decimalFormat.format((long) calendar.get(11)); String minute = decimalFormat.format((long) calendar.get(12)); String second = decimalFormat.format((long) calendar.get(13)); stringBuffer.append(year.substring(2, year.length())).append(month).append(day).append(hour).append(minute).append(second).append(decimalFormat.format((long) (calendar.get(7) - 1))); System.out.println(stringBuffer.toString()); return stringBuffer.toString(); }
Example #15
Source File: IKToolPanel.java From opensim-gui with Apache License 2.0 | 5 votes |
/** Creates new form IKToolPanel */ public IKToolPanel(Model model) throws IOException { if(model==null) throw new IOException("IKToolPanel got null model"); ikToolModel = new IKToolModel(model); if (numFormat instanceof DecimalFormat) { ((DecimalFormat) numFormat).applyPattern("###0.#########"); } helpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { BrowserLauncher.openURL("https://simtk-confluence.stanford.edu/display/OpenSim40/Inverse+Kinematics"); } }); initComponents(); bindPropertiesToComponents(); setSettingsFileDescription("IK tool settings file"); jTabbedPane.addTab("Weights", new IKTaskSetPanel(ikToolModel.getIKCommonModel())); markerFileName.setExtensionsAndDescription(".trc", "IK trial marker data"); coordinateFileName.setExtensionsAndDescription(".mot,.sto", "Coordinates of IK trial"); outputMotionFilePath.setExtensionsAndDescription(".mot", "Result motion file for IK"); outputMotionFilePath.setIncludeOpenButton(false); outputMotionFilePath.setDirectoriesOnly(false); outputMotionFilePath.setCheckIfFileExists(false); outputMotionFilePath.setSaveMode(true); updateModelDataFromModel(); updateFromModel(); ikToolModel.addObserver(this); }
Example #16
Source File: DecimalFormatTest.java From j2objc with Apache License 2.0 | 5 votes |
public void test_equals() { DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US); DecimalFormat cloned = (DecimalFormat) format.clone(); cloned.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); assertEquals(format, cloned); Currency c = Currency.getInstance(Locale.US); cloned.setCurrency(c); assertEquals(format, cloned); }
Example #17
Source File: MarkerDataInfoPanel.java From opensim-gui with Apache License 2.0 | 5 votes |
/** Creates new form TRCFileInfoPanel */ public MarkerDataInfoPanel() { if (doubleFormat instanceof DecimalFormat) { ((DecimalFormat) doubleFormat).applyPattern("###0.#########"); } initComponents(); }
Example #18
Source File: Function.java From proteus with Apache License 2.0 | 5 votes |
@NonNull @Override public Value call(Context context, Value data, int dataIndex, Value... arguments) throws Exception { double number = Double.parseDouble(arguments[0].getAsString()); DecimalFormat formatter = getFormatter(arguments); formatter.setRoundingMode(RoundingMode.FLOOR); formatter.setMinimumFractionDigits(0); formatter.setMaximumFractionDigits(2); return new Primitive(formatter.format(number)); }
Example #19
Source File: TopBlockMarketEntity.java From stockMarket with MIT License | 5 votes |
public TopBlockMarketEntity(String strEastMoney){ String [] strList = strEastMoney.split(","); //保留两位2小数 DecimalFormat decimalFormat=new DecimalFormat(".00"); this.blockCode = strList[1]; this.blockName = strList[2]; this.blockIncreasePercent = MyTime.convertEastMoneyFloat(strList[3]); this.TopStockCode = strList[7]; this.TopStockName = strList[9]; this.TopStockIncreasePercent = MyTime.convertEastMoneyFloat(strList[11]); }
Example #20
Source File: TieRoundingTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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 #21
Source File: NumericToCharFunctions.java From dremio-oss with Apache License 2.0 | 5 votes |
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 #22
Source File: MaterialsList.java From Ic2ExpReactorPlanner with GNU General Public License v2.0 | 5 votes |
@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 #23
Source File: StandardCategoryToolTipGeneratorTests.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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 #24
Source File: ExportingDialog.java From apkextractor with GNU General Public License v3.0 | 5 votes |
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 #25
Source File: QueueCLI.java From hadoop with Apache License 2.0 | 5 votes |
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 #26
Source File: Creature.java From dctb-utfpr-2018-1 with Apache License 2.0 | 5 votes |
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 #27
Source File: Bin.java From streaminer with Apache License 2.0 | 5 votes |
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 #28
Source File: DataFormatter.java From lams with GNU General Public License v2.0 | 5 votes |
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 #29
Source File: TestgetPatternSeparator_ja.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
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 #30
Source File: DataTypes.java From metanome-algorithms with Apache License 2.0 | 5 votes |
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; } }