當前位置: 首頁>>代碼示例>>Java>>正文


Java NumberFormat.format方法代碼示例

本文整理匯總了Java中java.text.NumberFormat.format方法的典型用法代碼示例。如果您正苦於以下問題:Java NumberFormat.format方法的具體用法?Java NumberFormat.format怎麽用?Java NumberFormat.format使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.text.NumberFormat的用法示例。


在下文中一共展示了NumberFormat.format方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: benchFormatAllNines

import java.text.NumberFormat; //導入方法依賴的package包/類
private static String benchFormatAllNines(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double[] decimaAllNines =
        {9.9993, 99.9993, 999.9993, 9999.9993, 99999.9993,
         999999.9993, 9999999.9993, 99999999.9993, 999999999.9993};
    double[] currencyAllNines =
        {9.993, 99.993, 999.993, 9999.993, 99999.993,
         999999.993, 9999999.993, 99999999.993, 999999999.993};
    double[] valuesArray = (isCurrency) ? currencyAllNines : decimaAllNines;
    double seed = 1.0 / (double) MAX_RANGE;
    double d;
    int id;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        id = (j >=  0) ? j % 9 : -j % 9;
        if ((j & 1) == 0)
            d = valuesArray[id] + id * seed;
        else
            d = valuesArray[id] - id * seed;
        str = nf.format(d);
    }
    return str;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:FormatMicroBenchmark.java

示例2: convertByteTo

import java.text.NumberFormat; //導入方法依賴的package包/類
public String convertByteTo(long byteData){
	NumberFormat formatter = NumberFormat.getInstance();
	formatter.setMaximumFractionDigits(2);
	try {
		double kb = byteData/1024L;
		if(kb >= 1024){
			double mb = kb/1024L;
			if(mb >= 1024){
				double gb = mb/1024L;
				return formatter.format(gb) +" GB";
			}else
				return  formatter.format(mb)+" MB";
		}else{				
			return formatter.format(kb)+" KB";
		}

	} catch (Exception e) {
		// TODO: handle exception
		return String.valueOf(byteData);
	}
}
 
開發者ID:mityung,項目名稱:XERUNG,代碼行數:22,代碼來源:Comman.java

示例3: percent2

import java.text.NumberFormat; //導入方法依賴的package包/類
public static String percent2(double p1, double p2) {
    String str;
    double p3 = p1 / p2;
    NumberFormat nf = NumberFormat.getPercentInstance();
    nf.setMinimumFractionDigits(0);
    str = nf.format(p3);
    return str;
}
 
開發者ID:snowwolf10285,項目名稱:PicShow-zhaipin,代碼行數:9,代碼來源:DeviceUtils.java

示例4: setDiliverPer

import java.text.NumberFormat; //導入方法依賴的package包/類
public static String setDiliverPer(int diliverNum, int queryMailNum) {
	NumberFormat numberFormat = NumberFormat.getInstance();
	// 設置精確到小數點後2位
	numberFormat.setMaximumFractionDigits(2);
	String result = numberFormat.format((float) diliverNum / (float) queryMailNum * 100);
	return result;
}
 
開發者ID:babymm,項目名稱:mumu,代碼行數:8,代碼來源:DiliverPerUtil.java

示例5: onCreate

import java.text.NumberFormat; //導入方法依賴的package包/類
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_consumption);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null)
        actionBar.setDisplayHomeAsUpEnabled(true);

    consumptionPerDay = getIntent().getFloatExtra(CONSUMPTION_PER_DAY, 0);

    consumptionTv = findViewById(R.id.consumption_tv);
    float consumptionPerYear = consumptionPerDay * NUMBER_OF_DAYS_PER_YEAR;
    NumberFormat format = NumberFormat.getInstance();
    String consumptionStr = format.format(consumptionPerYear) + getString(R.string.energy_unit);
    consumptionTv.setText(consumptionStr);

    float cost;
    if (consumptionPerDay > FIRST_TIER_MAX)
        cost = FIRST_TIER_MAX * ENERGY_COST_FIRST_TIER + (consumptionPerDay - FIRST_TIER_MAX) * ENERGY_COST_SECOND_TIER;
    else
        cost = consumptionPerDay * ENERGY_COST_FIRST_TIER;
    cost = cost * NUMBER_OF_DAYS_PER_YEAR;

    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    String costStr = moneyFormat.format(cost);
    costTv = findViewById(R.id.cost_tv);
    costTv.setText(costStr);
}
 
開發者ID:Sonphil,項目名稱:PhantomConsumptionCalculator,代碼行數:29,代碼來源:ConsumptionActivity.java

示例6: formatOnPattern

import java.text.NumberFormat; //導入方法依賴的package包/類
private static void formatOnPattern(NumberFormat nf, String pattern,
        double number, String expected) {

    if (nf instanceof DecimalFormat) {
        ((DecimalFormat) nf).applyPattern(pattern);
    }

    String formatted = nf.format(number);
    if (!formatted.equals(expected)) {
        throw new RuntimeException("[FAILED: Unable to format the number"
                + " based on the pattern: '" + pattern + "', Expected : '"
                + expected + "', Found: '" + formatted + "']");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:15,代碼來源:Bug6609740.java

示例7: sendSuccessNotification

import java.text.NumberFormat; //導入方法依賴的package包/類
void sendSuccessNotification(double spent, String bought) {
    NumberFormat formatter = new DecimalFormat("#0.00");
    String spentString = formatter.format(spent);

    trackBuy(bought, spentString);

    sendNotification("Bought " + bought + " " + preferences.getCryptoCurrency(), "Paid " + spentString + " " + preferences.getBaseCurrency(), -1);
}
 
開發者ID:aomega08,項目名稱:Keep-HODLing,代碼行數:9,代碼來源:BuyEvent.java

示例8: test

import java.text.NumberFormat; //導入方法依賴的package包/類
private static void test() {

        File root = new File("C:\\");
        System.out.println("Root Exists: " + root.exists());
        System.out.println("Root Absolute Path: " + root.getAbsolutePath());
        System.out.println("Root Is Directory?: " + root.isDirectory());

        FileSystemView fileSystemView = FileSystemView.getFileSystemView();
        NumberFormat nf = NumberFormat.getNumberInstance();

        int iMax = 50000;
        long lastPercentFinished = 0L;
        for (int i = 0; i < iMax; i++) {

            long percentFinished = Math.round(((i * 1000d) / (double) iMax));

            if (lastPercentFinished != percentFinished) {
                double pf = ((double) percentFinished) / 10d;
                String pfMessage = String.valueOf(pf) + " % (" + i + "/" + iMax + ")";

                long totalMemory = Runtime.getRuntime().totalMemory() / 1024;
                long freeMemory = Runtime.getRuntime().freeMemory() / 1024;
                long maxMemory = Runtime.getRuntime().maxMemory() / 1024;
                String memMessage = "[Memory Used: " + nf.format(totalMemory) +
                                    " kb Free=" + nf.format(freeMemory) +
                                    " kb Max: " + nf.format(maxMemory) + " kb]";

                System.out.println(pfMessage + " " + memMessage);
                lastPercentFinished = percentFinished;
            }

            boolean floppyDrive = fileSystemView.isFloppyDrive(root);
            boolean computerNode = fileSystemView.isComputerNode(root);

            // "isDrive()" seems to be the painful method...
            boolean drive = fileSystemView.isDrive(root);
        }
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:39,代碼來源:FileSystemViewMemoryLeak.java

示例9: getAllCurrencyNoWallet

import java.text.NumberFormat; //導入方法依賴的package包/類
public static String getAllCurrencyNoWallet(EntityPlayer player) {
	float currencyTotal = 0;

	for (int i = 0; i < player.inventory.getSizeInventory(); i++) {
		if (player.inventory.getStackInSlot(i) != ItemStack.EMPTY && player.inventory.getStackInSlot(i).getItem() instanceof ItemMoneyBase) {
			ItemMoneyBase money = (ItemMoneyBase) player.inventory.getStackInSlot(i).getItem();
			currencyTotal += (money.getValue() * player.inventory.getStackInSlot(i).getCount());
		}
	}

	NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
	return fmt.format(currencyTotal);
}
 
開發者ID:Zundrel,項目名稱:Never-Enough-Currency,代碼行數:14,代碼來源:CurrencyUtils.java

示例10: getMaxPossibleBuffer

import java.text.NumberFormat; //導入方法依賴的package包/類
public static String getMaxPossibleBuffer(Profile profile) {
    double minRatio = profile.response.stats.requiredRatio;
    double dl = bytesToGibiBytesDouble(profile.response.stats.downloaded);
    double ul = bytesToGibiBytesDouble(profile.response.stats.uploaded);

    double maxDl = ul / minRatio;
    double buffer = maxDl - dl;
    NumberFormat formatter = new DecimalFormat("#0.00");
    return formatter.format(buffer);
}
 
開發者ID:stuxo,項目名稱:REDAndroid,代碼行數:11,代碼來源:Calculator.java

示例11: formatOutputTestObject

import java.text.NumberFormat; //導入方法依賴的package包/類
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);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:41,代碼來源:TieRoundingTest.java

示例12: getDateString

import java.text.NumberFormat; //導入方法依賴的package包/類
private static String getDateString() {
	String out = "";
	NumberFormat formatter = new DecimalFormat("00");
	NumberFormat formatter1 = new DecimalFormat("000");

	int hours = Calendar.getInstance().get(Calendar.HOUR);
	int minutes = Calendar.getInstance().get(Calendar.MINUTE);
	int seconds = Calendar.getInstance().get(Calendar.SECOND);
	int msec = Calendar.getInstance().get(Calendar.MILLISECOND);

	out = formatter.format(hours)+":"+formatter.format(minutes)+":"+formatter.format(seconds)+":"+formatter1.format(msec);
	return out;
}
 
開發者ID:ZetzmannM,項目名稱:CGL,代碼行數:14,代碼來源:StatusPrinter.java

示例13: setFileSizeSave

import java.text.NumberFormat; //導入方法依賴的package包/類
public void setFileSizeSave(long size){
	NumberFormat nf=NumberFormat.getNumberInstance() ; 
	nf.setMaximumFractionDigits(2);
	if(size<1024){
		fileSize =nf.format(size) +"B";
	}else if(size<1024*1024){
		this.fileSize =nf.format(size/1024.0) + "KB";
	}else if(size<1024*1024*1024){
		this.fileSize = nf.format(size/1024.0 * 1024) + "MB";
	}else if(size<1024*1024*1024*1024){
		this.fileSize = nf.format(size/1024.0 * 1024 * 1024) + "GB";
	}	
}
 
開發者ID:ranji1221,項目名稱:clemon,代碼行數:14,代碼來源:BackupDatabaseInfo.java

示例14: benchFormatSmallIntegral

import java.text.NumberFormat; //導入方法依賴的package包/類
private static String benchFormatSmallIntegral(NumberFormat nf) {
    String str = "";
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++)
        str = nf.format(((double) j) / 1000.0d);
    return str;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:7,代碼來源:FormatMicroBenchmark.java

示例15: formatOutputTestDouble

import java.text.NumberFormat; //導入方法依賴的package包/類
static void formatOutputTestDouble(NumberFormat nf,
                                   double doubleToTest,
                                   String tiePosition,
                                   String inputDigits,
                                   String expectedOutput) {

    int mfd = nf.getMaximumFractionDigits();
    RoundingMode rm = nf.getRoundingMode();
    String result = nf.format(doubleToTest);

    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("BigDecimal output : " +
                           new BigDecimal(doubleToTest).toString());
        System.out.println("FloatingDecimal output : " + doubleToTest);
        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.println("\nSuccess for double value : " + doubleToTest + " :");
        System.out.println(" Input digits :" + inputDigits +
                           ", BigDecimal value : " +
                           new BigDecimal(doubleToTest).toString());
        System.out.print(" Rounding mode: " + rm);
        System.out.print(", fract digits : " + mfd);
        System.out.print(", position : " + tiePosition + " tie");
        System.out.print(", result : " + result);
        System.out.println(", expected : " + expectedOutput);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:47,代碼來源:TieRoundingTest.java


注:本文中的java.text.NumberFormat.format方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。