Java Code Examples for java.text.DecimalFormat#format()

The following examples show how to use java.text.DecimalFormat#format() . 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: $.java    From pysonar2 with Apache License 2.0 6 votes vote down vote up
public static String printMem(long bytes) {
    double dbytes = (double) bytes;
    DecimalFormat df = new DecimalFormat("#.##");

    if (dbytes < 1024) {
        return df.format(bytes);
    } else if (dbytes < 1024 * 1024) {
        return df.format(dbytes / 1024);
    } else if (dbytes < 1024 * 1024 * 1024) {
        return df.format(dbytes / 1024 / 1024) + "M";
    } else if (dbytes < 1024 * 1024 * 1024 * 1024L) {
        return df.format(dbytes / 1024 / 1024 / 1024) + "G";
    } else {
        return "Too big to show you";
    }
}
 
Example 2
Source File: EasyMoneyTextView.java    From EasyMoney-Widgets with Apache License 2.0 6 votes vote down vote up
private String getDecoratedStringFromNumber(long number)
{
    String numberPattern = "#,###,###,###";
    String decoStr = "";

    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
    if (_showCommas && !_showCurrency)
        formatter.applyPattern(numberPattern);
    else if (_showCommas && _showCurrency)
        formatter.applyPattern(_currencySymbol + " " + numberPattern);
    else if (!_showCommas && _showCurrency)
        formatter.applyPattern(_currencySymbol + " ");
    else if (!_showCommas && !_showCurrency)
    {
        decoStr = number + "";
        return decoStr;
    }

    decoStr = formatter.format(number);

    return decoStr;
}
 
Example 3
Source File: DialogHelper.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
public static String createLogFilename() {
    Date date = new Date();
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(date);

    DecimalFormat twoDigitDecimalFormat = new DecimalFormat("00");
    DecimalFormat fourDigitDecimalFormat = new DecimalFormat("0000");

    String year = fourDigitDecimalFormat.format(calendar.get(Calendar.YEAR));
    String month = twoDigitDecimalFormat.format(calendar.get(Calendar.MONTH) + 1);
    String day = twoDigitDecimalFormat.format(calendar.get(Calendar.DAY_OF_MONTH));
    String hour = twoDigitDecimalFormat.format(calendar.get(Calendar.HOUR_OF_DAY));
    String minute = twoDigitDecimalFormat.format(calendar.get(Calendar.MINUTE));
    String second = twoDigitDecimalFormat.format(calendar.get(Calendar.SECOND));

    return year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + ".txt";
}
 
Example 4
Source File: FmtFunc.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 对象格式化
 * @param object 格式化对象
 * @param pattern 表达式
 * @return 格式化后的字符串
 */
public String format(Object object, String pattern) {
	if (object instanceof Number) {
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		return decimalFormat.format(object);
	} else if (object instanceof Date) {
		return DateUtil.format((Date) object, pattern);
	} else if (object instanceof TemporalAccessor) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
		return df.format((TemporalAccessor) object);
	}
	throw new MicaTplException("未支持的对象格式" + object);
}
 
Example 5
Source File: EditAlertActivity.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public static String unitsConvert2Disp(boolean doMgdl, double threshold) {
    DecimalFormat df = getNumberFormatter(doMgdl);
    if (doMgdl)
        return df.format(threshold);

    return df.format(threshold / Constants.MMOLL_TO_MGDL);
}
 
Example 6
Source File: ReactionSimilarityTool.java    From ReactionDecoder with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
     *
     * @param alpha
     * @param beta
     * @param bondSimilarity
     * @param structuralSimilarity
     * @return
     * @throws CDKException
     */
    public static double getSimilarityScore(double alpha,
            double beta,
            double bondSimilarity,
            double structuralSimilarity) throws CDKException {

        double score = 0;
        // In maths S=e pow(x) * e pow(y) = e pow(x+y)
        double BC = bondSimilarity;
        double SC = structuralSimilarity;

        if (alpha == 0 && beta == 0) {
            throw new CDKException("Both alpha & beta can't be zero at the same time");
        } else if (BC == 0 && SC == 0) {
            score = 0;
        } else {
            double structureScore = (beta / (alpha + beta)) * SC;
            double bondScore = (alpha / (alpha + beta)) * BC;
            score = bondScore + structureScore;
        }
//        System.out.println("alpha: " + alpha + "\tbeta: " + beta + "\tBondSimilarity: " + BC + "\tStructuralSimilarity: " + SC + "\tScore: " + score);

        DecimalFormat df = new DecimalFormat("0.00");
        df.setMaximumFractionDigits(2);
        String a = df.format(score);
        score = parseDouble(a);
        return score;
    }
 
Example 7
Source File: Unitized.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String unitized_string_static_no_interpretation_short(double value) {
    final boolean domgdl = Pref.getString("units", "mgdl").equals("mgdl");
    final DecimalFormat df = new DecimalFormat("#");
    if (domgdl) {
        df.setMaximumFractionDigits(0);
    } else {
        df.setMaximumFractionDigits(1);
    }
    return df.format(unitized(value, domgdl)) + " " + (domgdl ? "mgdl" : "mmol");
}
 
Example 8
Source File: TestOrderBy.java    From spork with Apache License 2.0 5 votes vote down vote up
public TestOrderBy() throws Throwable {
    DecimalFormat myFormatter = new DecimalFormat("0000000");
    for (int i = 0; i < DATALEN; i++) {
        DATA[0][i] = myFormatter.format(i);
        DATA[1][i] = myFormatter.format(DATALEN - i - 1);
    }
    pig = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
}
 
Example 9
Source File: Player.java    From pmTrans with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getElapsedTimeString() {
	DecimalFormat twoDigit = new DecimalFormat("#0.0");
	return secondsToString(getMediaTime())
			+ "/"
			+ secondsToString(getDuration())
			+ " ("
			+ twoDigit.format(100 * getMediaTime()
					/ (getDuration() == 0 ? 1 : getDuration())) + ")% ";
}
 
Example 10
Source File: Complex.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * Print a String with the distribution
 * </p>
 * @return                      Complete distribution for the classes
 */
public String printDistribucionString() {

    DecimalFormat d = new DecimalFormat("0.00");

    String cad = new String("\n[");
    for (int i = 0; i < nClasses; i++) {
        cad += "  " + d.format(distrib[i]);
    }
    cad += "  ]\n";
    return cad;
}
 
Example 11
Source File: Strings.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
public static String concat(float[] s, DecimalFormat f, Pattern t) {
    String[] str = new String[s.length];
    for (int i = 0; i < s.length; i++) {
        str[i] = "" + f.format(s[i]);
    }
    return concat(str, t);
}
 
Example 12
Source File: RemovingDecimalsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
    DecimalFormat df = new DecimalFormat("#,###");
    df.setRoundingMode(RoundingMode.FLOOR);
    String truncated = df.format(doubleValue);
    assertEquals("345", truncated);
}
 
Example 13
Source File: SendingTokensActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void updateFee() {

        BigInteger defaultGasLimit = BigInteger.valueOf(DEFAULT_GAS_LIMIT_FOR_CONTRACT);
        BigInteger fee = gasPrice.multiply(defaultGasLimit);
        currentFeeEth = new BigDecimal("0");//Convert.fromWei(new BigDecimal(fee), Convert.Unit.ETHER);
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
        symbols.setDecimalSeparator('.');
        DecimalFormat decimalFormat = new DecimalFormat("##0.#####", symbols);
        String feeStr = decimalFormat.format(currentFeeEth);
        etFeeAmount.setText(feeStr);
    }
 
Example 14
Source File: QuoteData.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
public String getChangeHTML() {
    String htmlString, arrow;
    if (change < 0.0) {
        htmlString = "<FONT color=\"#cc0000\">";
        arrow = "arrowdown.gif";
    } else {
        htmlString = "<FONT color=\"#009900\">";
        arrow = "arrowup.gif";
    }
    DecimalFormat df = new DecimalFormat("####0.00");

    htmlString += df.format(change) + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>";
    return htmlString;
}
 
Example 15
Source File: NikonType2MakernoteDescriptor.java    From sagetv with Apache License 2.0 5 votes vote down vote up
public String getAutoFlashCompensationDescription() throws MetadataException
{
    Rational ev = getMakernoteDirectory().getAutoFlashCompensation();

    if (ev==null)
        return "Unknown";

    DecimalFormat decimalFormat = new DecimalFormat("0.##");
    return decimalFormat.format(ev.floatValue()) + " EV";
}
 
Example 16
Source File: ResultFormatter.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * Formats the given double values.
 * @param val The double value to format.
 * @return The formatted double value.
 */
public String format(double val)
{
  DecimalFormat df = getDoubleFormat();

  if (df != null) {
    return df.format(val);
  }

  return Double.toString(val);
}
 
Example 17
Source File: WalkModFacade.java    From walkmod-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void updateMsg(long startTime, Exception e) {
    if (options.isVerbose()) {
        DecimalFormat myFormatter = new DecimalFormat("###.###");
        DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.US);
        long endTime = System.currentTimeMillis();
        double time = 0;
        if (endTime > startTime) {
            time = (double) (endTime - startTime) / (double) 1000;
        }
        String timeMsg = myFormatter.format(time);
        System.out.print("----------------------------------------");
        System.out.println("----------------------------------------");
        if (e == null) {
            log.info("CONFIGURATION UPDATE SUCCESS");
        } else {
            log.info("CONFIGURATION UPDATE FAILS");
        }
        System.out.println();
        System.out.print("----------------------------------------");
        System.out.println("----------------------------------------");
        log.info("Total time: " + timeMsg + " seconds");
        log.info("Finished at: " + df.format(new Date()));
        log.info("Final memory: " + (Runtime.getRuntime().freeMemory()) / 1048576 + " M/ "
                + (Runtime.getRuntime().totalMemory() / 1048576) + " M");
        System.out.print("----------------------------------------");
        System.out.println("----------------------------------------");

        if (e != null) {
            if (options.isPrintErrors()) {
                log.error("Plugin installations fails", e);
            } else {
                log.info("Plugin installations fails. Please, execute walkmod with -e to see the details");
            }
            if (options.isThrowException()) {
                RuntimeException re = new RuntimeException();
                re.setStackTrace(e.getStackTrace());
                throw re;
            }
        }
    }
}
 
Example 18
Source File: CalcUtils.java    From SmallGdufe-Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 求score分数对应的绩点,如90分为4.0,返回字符串"4.0"
 * @param score
 * @return
 */
public static String calcScore2Gpa(int score) {
    if (score < 60) return "0.0";
    DecimalFormat df = new DecimalFormat("#.0");
    return df.format(1.0 + (score - 60) * 0.1);
}
 
Example 19
Source File: JkChatUtils.java    From HttpRequest with Apache License 2.0 2 votes vote down vote up
/**
 * 保留两位小数
 * @author leibing
 * @createTime 2017/3/13
 * @lastModify 2017/3/13
 * @param num
 * @return
 */
public static String doubleTwoDecimal(Double num){
    DecimalFormat df  = new DecimalFormat("######0.00");
    return df.format(num);
}
 
Example 20
Source File: DataWriterUtil.java    From parso with Apache License 2.0 2 votes vote down vote up
/**
 * The function to convert a percent element into a string.
 *
 * @param value         the input numeric value to convert.
 * @param decimalFormat the formatter to convert percentage element into string.
 * @return the string with the text presentation of the input numeric value.
 */
private static String convertPercentElementToString(Object value, DecimalFormat decimalFormat) {
    Double doubleValue = value instanceof Long ? ((Long) value).doubleValue() : (Double) value;
    return decimalFormat.format(doubleValue);
}