2017-07-06 21 views

回答

2

可以使用rexgex做格式化

1)創建一個樂趣ction識別下列條件

  • 如果精度值只包含零,然後截斷這些

  • 如果小數點後任何非零值,則返回原始值

    public String formatValue(double d){ 
        String dStr = String.valueOf(d); 
        String value = dStr.matches("\\d+\\.\\d*[1-9]\\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));  
        return value; 
    } 
    

\\d+\\.\\d*[1-9]\\d*:匹配一個或多個數字然後輸入.

  • \\d*[1-9]\\d*:匹配一個非零值

測試用例

yourTextView.setText(formatValue(500.00000000)); // 500 
    yourTextView.setText(formatValue(500.0001));  // 500.0001 
    yourTextView.setText(formatValue(500));   // 500 
    yourTextView.setText(formatValue(500.1111));  // 500.1111 

Learn more about regular expressions

+2

這應該是完美的答案。 –

+0

這真棒,謝謝! – Den

+0

我很高興能幫上忙 –

-1

您需要使用方法的intValue()這樣明確的將int值:

雙d = 5.25; Integer i = d.intValue();

或 double d = 5.25; int i =(int)d;

+1

請添加一個有價值的鏈接,使其成爲更好的答案。 –

+0

@YagamiLight當然。 http://javarevisited.blogspot.com/2017/01/how-to-convert-double-to-int-in-java.html http://www.studytonight.com/java/type-casting- in-java – ZaidBinAsif

2

使用DecimalFormat

double price = 500.0; 
DecimalFormat format = new DecimalFormat("0.###"); 
System.out.println(format.format(price)); 

編輯

好,比嘗試不同的東西:

public static String formatPrice (double price){ 
    if (price == (long) price) 
     return String.format("%d", (long) price); 
    else 
     return String.format("%s", price); 
} 
+0

將無法​​使用值'500.01'將返回'500' –

+0

是的,我需要刪除逗號,前提是零後出現。但如果價格= 12.50我需要顯示12.50。 – Den

+0

@Den嘗試第二個解決方案 – Pantsoffski

相關問題