2012-05-03 68 views
0

我想截斷Java中的float值。在Java 1.5中截斷float Float in setRoundingMode

以下是我的要求:

  1. ,如果我有12.49688f,應該如果是在雙印124.56爲12.49不四捨五入
  2. ,應打印爲12.45無四捨五入off
  3. 在任何情況下,如果值是12.0,則應該僅打印爲12。

條件3應該始終牢記在心,它應該與 截斷邏輯同時發生。

P.S:我正在使用Java 1.5。所以我知道如何在Java 1.6中使用Decimal Format並調用setroundingMode()方法。 我需要知道Java 1.5

回答

2

乘以,使用Math#floor並在將數字提供給DecimalFormat之前進行分割。這與截斷圓角相同。

// Replace N with the desired number of decimals after the comma 
number = Math.floor(1eN * number)/1eN 

這並不完美,因爲浮點計算中的舍入誤差,所以您仍然必須爲DecimalFormat指定N個小數。

 

A(更昂貴,也比較邏輯的)替代方法是使用一個BigDecimal

// Given as seperate statements for clarity, but these can be combined into a single line 
// Replace "N" with the number of decimals after the comma 
MathContext NDecimals = new MathContext(N, RoundingMode.FLOOR); 
BigDecimal bdNumber = new BigDecimal(number, NDecimals); 
number = bdNumber.doubleValue(); 
1

將其轉換爲字符串並在句點後的第二個數字後截斷任何內容。 修剪「0」和「。」如果有「。」

String x = Double.toString (12.456); // or Float.toString (12.49688f); 

int pos = x.indexOf ('.'); // 
if (pos >= 0) { 
    int end = Math.min(pos + 2, x.length() - 1); // truncate after 2 digits 
    while (x.charAt (end) == '0') end --; // trim 0 
    if (x.charAt (end) == '.') end --; // trim . 
    x = x.substring(0, end + 1);  // really truncate 
} 

(測試在我的環境,工程)

+0

它肯定有;) – Azfar

+0

@Azfar,我曾在我的地方 –

+0

@斯特凡bachert如果我輸入12.2它應該給我12.20? – Azfar