2012-05-03 16 views
6

好吧,也許我只需要第二雙眼睛就可以了。將字符串拆分爲字符串[]一段時間,但返回一個空數組

我有一個浮點數,我變成了一個字符串。然後,我想按照它的週期/小數分割它,以便將它作爲貨幣。

繼承人我的代碼:

float price = new Float("3.76545"); 
String itemsPrice = "" + price; 
if (itemsPrice.contains(".")){ 
    String[] breakByDecimal = itemsPrice.split("."); 
    System.out.println(itemsPrice + "||" + breakByDecimal.length); 
    if (breakByDecimal[1].length() > 2){ 
     itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1].substring(0, 2); 
    } else if (breakByDecimal[1].length() == 1){ 
     itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1] + "0";       
    }       
} 

如果拿這一點,並運行它,你會得到關於那裏是一個小數點後沒有數組索引出第6行界失誤(在上面的代碼)。

其實第5行,當我打印出數組的大小,它的0

這些都是可笑的錯誤讓他們不會有事我只是遠眺。

就像我說的,另一雙眼睛正是我需要的,所以當指出一些對你來說很明顯的東西時,請不要粗魯,但我忽略了它。

在此先感謝!

回答

19

分裂使用正則表達式,其中 「」意味着匹配任何角色。你需要做的

"\\." 

編輯:固定的,由於評論者&編輯

+1

或者使用Matcher.quoteReplacement() – xxpor

+0

很好,以前從未見過。謝謝... – ianpojman

+1

不,兩個反斜槓是正確的,否則你會在字面上匹配一個反斜槓然後一個點'\ .' – Bohemian

0

使用十進制格式,而不是:

DecimalFormat formater = new DecimalFormat("#.##"); 
System.out.println(formater.format(new Float("3.76545"))); 
+0

你應該使用NumberFormat.getCurrencyInstance實例化的NumberFormat( )在處理金錢時。 – xxpor

0

我沒有工作太多關於Java,但在第2行,也許價格不獲取轉換成字符串。我在C#中工作,我會用它作爲: String itemsPrice =「」+ price.ToString();

也許你應該明確地將價格轉換爲字符串。 因爲它沒有被轉換,字符串只包含「」,並且沒有「。」,所以沒有拆分和擴展arrayOutOfBounds錯誤。

0

如果您想將其作爲價格使用NumberFormat呈現。

Float price = 3.76545; 
Currency currency = Currency.getInstance(YOUR_CURRENCY_STRING); 
NumberFormat numFormat = NumberFormat.getCurrencyInstance(); 
numFormat.setCurrency(currency) 
numFormat.setMaximumFractionDigits(currency.getDefaultFractionDigits()); 
String priceFormatted = numFormat.format(price); 
System.out.println("The price is: " + priceFormatted); 

YOUR_CURRENCY_STRING是您所處理貨幣的ISO 4217貨幣代碼。

此外,以非精確格式(如浮點)表示價格通常是一個壞主意。您應該使用BigDecimal或Decimal。

0

如果你想自己來處理這一切,然後嘗試下面的代碼:

public static float truncate(float n, int decimalDigits) { 
    float multiplier = (float)Math.pow(10.0,decimalDigits); 
    int intp = (int)(n*multiplier); 
    return (float)(intp/multiplier); 
} 

,並得到這樣的truncatedPrice:

float truncatedPrice = truncate(3.3654f,2); 
System.out.println("Truncated to 2 digits : " + truncatedPrice);