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!
split uses regular expressions, in which "." means match any character. you need to do
"\\."
EDIT: fixed, thanks commenter&editor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With