2017-04-04 26 views
1

我必須根據不同的值以不同的值格式化Java中的float。例如將浮動格式化爲不同的精度

23 format to 23 
24.15 format to 24.15 
30.249 format to 30.25 
42.7 format to 42.7 

也就是說,從100位四捨五入,但不顯示最後的0到右側(即3.4,而不是3.40和7,而不是7.0)等,但再次小數點後兩位最大。

我在玩String.format,但無法弄清楚正確的格式。我確實需要格式化float並將其寫入String。

任何人都有一個想法應該是什麼格式,或其他方式來格式化數字(字符串)?

+0

可能的重複[如何在Java中顯示2位小數位數的float數據輸出?](http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float- data-with-2-decimal-places-in-java) –

回答

3

使用new DecimalFormat("0.##")

# - 數字,零顯示爲不存在

測試

NumberFormat fmt = new DecimalFormat("0.##"); 
System.out.println(fmt.format(23f)); 
System.out.println(fmt.format(24.15f)); 
System.out.println(fmt.format(30.249f)); 
System.out.println(fmt.format(42.7f)); 
System.out.println(fmt.format(53.006f)); 

輸出

23 
24.15 
30.25 
42.7 
53.01 
-1

要開始你想要添加.005到你的浮球,所以它適當地回合。

floatvariable = floatvariable+.005; 

然後,你需要乘以一百。

floatvariable = floavariable*100; 

現在你需要將它轉換爲一個整數,這將刪除任何額外的數字。

int intvariable = (int)floatvariable; 

最後,你可以把這個數字除以100,然後把它放回到float變量中。

floatvariable = (float)intvariable/100 

現在你應該有一個四捨五入到最接近的千分之一的數字。

+1

如果'floatvariable'是'float',則不會編譯。它也不會編譯,因爲'floavariable'拼寫錯誤。但是,最重要的是,如果初始值是'23',那麼會打印'23.0'。 OP想要打印'23'。 – Andreas