2011-12-01 27 views
4

我想改變浮動像這樣:在Java中,如何刪除float中的所有0?

10.5000 - > 10.5 10.0000 - > 10

如何刪除所有零小數點後,並改變它要麼浮動(如果有非-Zero)或int(如果只有零)?

在此先感謝。

+5

我不太明白。零點只是文本表示的產物,它們與浮點數如何在內部表示無關。你在尋找抑制尾隨零的自定義輸出格式嗎? –

回答

10

爲什麼不嘗試正則表達式?

new Float(10.25000f).toString().replaceAll("\\.?0*$", "") 
+0

這不太合理,因爲'new Float(10.25000f).toString()'已經給你「10.25」,所以'.replaceAll(「0 * $」,「」)'是沒有用的。 –

+1

'「\ .0 + $」'如果你想擺脫這段時間。 – Marcelo

+0

如果我將「0 * $」更改爲「\ .0 + $」,它會顯示「unexpected char:'。」 - 我正在處理中。 – clerksx

1

根據需要爲輸出格式化數字。您不能刪除內部的「0」值。

1

這兩種不同的格式化處理它:

double d = 10.5F; 
DecimalFormat formatter = new DecimalFormat("0"); 
DecimalFormat decimalFormatter = new DecimalFormat("0.0"); 
String s; 
if (d % 1L > 0L) s = decimalFormatter.format(d); 
else s = formatter.format(d); 

System.out.println("s: " + s); 
1

java.math.BigDecimal有一個stripTrailingZeros()方法,它可以實現你要找的東西。

BigDecimal myDecimal = new BigDecimal(myValue); 
myDecimal.stripTrailingZeros(); 
myValue = myDecimal.floatValue(); 
16

嘛訣竅是,花車和雙打自己真的沒有尾隨零本身;這只是它們打印(或初始化爲文字)的方式,可能會顯示它們。考慮這些例子:

Float.toString(10.5000); // => "10.5" 
Float.toString(10.0000); // => "10.0" 

可以使用DecimalFormat修復的「10.0」的例子:我有同樣的問題

new java.text.DecimalFormat("#").format(10.0); // => "10" 
+1

這解釋得更好。 +1。 –

+1

DecimalFormat的+1。另外使用半舍入的十進制格式。 http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html – HRgiger

+0

非常感謝。我沒有說明我實際上在處理Processing。正則表達式更簡單了我的情況。 – clerksx

0

,並找到在以下鏈接解決方法: StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0

JasonD的回答是我所遵循的。這不是由地區決定的,這對我的問題很有幫助,並且沒有長期價值的問題。

希望得到這個幫助。

添加內容從以上鍊接:

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

產地:

232 
0.18 
1237875192 
4.58 
0 
1.2345 
+0

你可以從鏈接中添加一些內容嗎? – Robert