2015-09-21 93 views
3

第一篇文章。我一般都是軟件開發方面的新手,並花了數小時的時間試圖弄清楚這件事。如您所見,我將double轉換爲String,然後將該值分配給textResultString)。我正確格式化它以顯示小數,但我無法弄清楚如何顯示爲貨幣。顯示貨幣格式問題

基於我已經在網上找到的,它看起來像我可能不得不使用

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); 

然後用nf.format()莫名其妙,但它只是不爲我工作。任何指導將不勝感激。

public void onCalculateDealOne(View v) { 

    //get values from text fields 
    EditText priceEntry = (EditText) findViewById(R.id.etListPriceDealOne); 
    EditText unitsEntry = (EditText) findViewById(R.id.etNumberOfUnitsDealOne); 
    EditText couponEntry = (EditText) findViewById(R.id.etCouponAmountDealOne); 


    //get value from result label 
    TextView result = (TextView) findViewById(R.id.perUnitCostDealOne); 

    //assign entered values to int variables 
    double price = Double.parseDouble(priceEntry.getText().toString()); 
    double units = Double.parseDouble(unitsEntry.getText().toString()); 
    double coupon = Double.parseDouble(couponEntry.getText().toString()); 

    //create variable that holds the calculated result and then do the math 
    double calculatedResultDealOne = (price - coupon)/units; 

    //convert calculatedResult to string 
    String textResult = String.format("%.3f", calculatedResultDealOne); 
    result.setText(textResult + " per unit"); 
    dealOneValue = calculatedResultDealOne; 

    //hide the keyboard 
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 

    //make deal one label visible 
    result.setVisibility(View.VISIBLE); 

} 

回答

1

您需要使用格式化來格式化你想要的雙重價值,如:

double money = 202.2 
NumberFormat formatter = NumberFormat.getCurrencyInstance(); 
String moneyString = formatter.format(money); 
System.out.println(moneyString); 
2

達到這一目的有兩個簡單的解決方案。您可以使用DecimalFormat對象,也可以使用NumberFormat對象。

我個人更喜歡Decimalformat對象,因爲它可以更精確地控制如何設置輸出值/文本的格式。

某些人可能更喜歡NumberFormat對象,因爲.getcurrencyInstance()方法比隱藏字符串格式(例如「$#00」,「#0.00」)更容易理解。

public static void main(String[] args) { 
    Double currency = 123.4; 
    DecimalFormat decF = new DecimalFormat("$#.00"); 

    System.out.println(decF.format(currency)); 

    Double numCurrency = 567.89; 
    NumberFormat numFor = NumberFormat.getCurrencyInstance(); 
    System.out.println(numFor.format(numCurrency)); 
} 

輸出這個例子程序是如下:

$ 123.40

$ 567.89