Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String to String[] by a period but returning an empty array

Ok maybe i just need a second pair of eyes on this.

I have a float, that I turn into a string. I then want to split it by its period/decimal in order to present it as a currency.

Heres my code:

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";                         
    }                           
}

If you take this and run it, you will get an array index out of bounds error on line 6 (in the code above) regarding there being nothing after a decimal.

In fact on line 5, when i print out the size of the array, it's 0.

These are to ridiculous of errors for them to NOT be something i am simply overlooking.

Like I said, another pair of eyes is exactly what i need, so please don't be rude when pointing out something that's obvious to you but I overlooked it.

Thanks in advance!

like image 496
Kamron K. Avatar asked May 03 '12 04:05

Kamron K.


1 Answers

split uses regular expressions, in which "." means match any character. you need to do

"\\."

EDIT: fixed, thanks commenter&editor

like image 154
ianpojman Avatar answered Nov 14 '22 20:11

ianpojman