org.apache.http.impl.client.SystemDefaultHttpClient#java.text.DecimalFormat源码实例Demo

下面列出了org.apache.http.impl.client.SystemDefaultHttpClient#java.text.DecimalFormat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: DMusic   文件: Util.java
/**
 * 返回数据大小(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";
    }
}
 
源代码2 项目: buffer_bci   文件: RelativeDateFormat.java
/**
 * 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");
}
 
源代码3 项目: ASTRAL   文件: AbstractInference.java
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);

}
 
源代码4 项目: pentaho-kettle   文件: RowGeneratorMeta.java
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";
}
 
源代码5 项目: hottub   文件: NumberFormatProviderImpl.java
/**
 * 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);
            }
        }
    }
}
 
源代码6 项目: sailfish-core   文件: FIXMatrixUtil.java
@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);
}
 
源代码7 项目: morpheus-core   文件: Parser.java
/**
 * 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);
        }
    });
}
 
源代码8 项目: javaanpr   文件: RecognitionPerformanceIT.java
/**
 * 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());
}
 
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.");
}
 
源代码10 项目: jts   文件: SVGWriter.java
/**
 *  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);
}
 
源代码11 项目: closure-stylesheets   文件: GssFunctions.java
@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());
}
 
源代码12 项目: ECG-Viewer   文件: StandardTickUnitSource.java
/**
 * 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"));
}
 
源代码13 项目: tsml   文件: kNN.java
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);
    }
 
源代码14 项目: FimiX8-SDFG   文件: ByteHexHelper.java
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();
}
 
源代码15 项目: opensim-gui   文件: IKToolPanel.java
/** 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);
}
 
源代码16 项目: j2objc   文件: DecimalFormatTest.java
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);
}
 
源代码17 项目: opensim-gui   文件: MarkerDataInfoPanel.java
/** Creates new form TRCFileInfoPanel */
public MarkerDataInfoPanel() {
   if (doubleFormat instanceof DecimalFormat) {
     ((DecimalFormat) doubleFormat).applyPattern("###0.#########");
   }

   initComponents();
}
 
源代码18 项目: proteus   文件: Function.java
@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));
}
 
源代码19 项目: stockMarket   文件: TopBlockMarketEntity.java
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]);
}
 
源代码20 项目: openjdk-jdk9   文件: TieRoundingTest.java
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);
    }
}
 
源代码21 项目: dremio-oss   文件: NumericToCharFunctions.java
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);
}
 
源代码22 项目: Ic2ExpReactorPlanner   文件: MaterialsList.java
@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();
}
 
/**
 * 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));
}
 
源代码24 项目: apkextractor   文件: ExportingDialog.java
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+"%)");
}
 
源代码25 项目: hadoop   文件: QueueCLI.java
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());
}
 
源代码26 项目: dctb-utfpr-2018-1   文件: Creature.java
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(",", ".")));
}
 
源代码27 项目: streaminer   文件: Bin.java
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;
}
 
源代码28 项目: lams   文件: DataFormatter.java
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;
    }
}
 
源代码29 项目: jdk8u_jdk   文件: TestgetPatternSeparator_ja.java
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");
    }
}
 
源代码30 项目: metanome-algorithms   文件: DataTypes.java
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;
  }
}