Java – splits a string into string [] for a period of time, but returns an empty array

Well, maybe I just need a second pair of eyes

I have a floating point number and I become a string Then I want to split it with its period / decimal so that it can be expressed as currency

Inherit 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), with nothing after the decimal

In fact, on line 5, when I print out the size of the array, it is 0

For them, these are absurd mistakes, not things I just ignore

As I said, another pair of eyes is exactly what I need, so please don't be rude when pointing out something obvious to you, but I ignored it

Thank you in advance!

Solution

Split uses a regular expression where "." It means matching any role What you need to do

"\\."

Editor: fix, thanks to reviewers and editors

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>