1

The operation I'm hoping to perform is to go from:

String "32.63578..."

to:

float 32.63
long 578... //where '...' is rest of string

Something like the following in Python:

split = str.find('.')+2
float = str[:split]
long = str[split:]

I'm new to Java, so I began by trying to look up equivalents, however it seems like a more convoluted solution than perhaps a regex would be? Unless there's more similar functions to python than splitting into a char array, and repeatedly iterating over?

OJFord
  • 10,522
  • 8
  • 64
  • 98

4 Answers4

5

Use indexOf and substring methods:

String str = "32.63578";
int i = str.indexOf(".") + 3;
String part1 = str.substring(0, i);     // "32.63"
String part2 = str.substring(i);        // "578"

float num1 = Float.parseFloat(part1);   // 32.63
long num2 = Long.parseLong(part2);      // 578
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

Regular expression alternative:

String str = "32.63578";
String[] parts = str.split("(?<=\\.\\d{2})");
System.out.println(parts[0]); // "32.63"
System.out.println(parts[1]); // "578"

About the regular expression used:

(?<=\.\d{2})

It's positive lookbehind (?<=...). It matches at the position where is preceded by . and 2 digits.

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

You can use the split method in String if you want to cleanly break the two parts.

However, if you want to have trailing decimals like in your example, you'll probably want to do something like this:

String str = "32.63578...";
String substr1, substr2;

for (int i = 0; i < str.length(); i++)
{
  if (str.charAt(i) == '.')
  {
    substr1 = str.substring(0, i + 3);
    substr2 = str.substring(i + 3, str.length());
    break;
  }
}

//convert substr1 and substr2 here
Mobin Skariya
  • 392
  • 3
  • 12
yossarian
  • 1,537
  • 14
  • 21
0
String s ="32.63578";
    Pattern pattern = Pattern.compile("(?<Start>\\d{1,10}.\\d{1,2})(?<End>\\d{1,10})");
    Matcher match = pattern.matcher(s);
    if (match.find()) {
        String start = match.group("Start");
        String ending = match.group("End");
        System.out.println(start);
        System.out.println(ending);
    }
Maheshbabu Jammula
  • 357
  • 1
  • 2
  • 11