2

I need help with a function in my android application. The function obtain a double like this: 0.1234567 or 123.1234567; and I would like convert this to string and later, if the double is greater than 1 it must return 123.1 (if the double is 123.123456) and if the double is less than 0, it must return 123 (if the double is 0.123456). For the time being, I managed to convert the double to string but I dont know how to do this.

This is my method:

public String getFormatDistance(double distance) {
        String doubleAsText = String.valueOf(distance);
        if (distance > 0.9) {
            return doubleAsText;
        } else {
            String[] parts = doubleAsText.split(".");
            String part1 = parts[0];
            String part2 = parts[1];
            //part2 = part2.split("");
            return part2;
        }
    }

This lines shows the string:

    TextView fourText = (TextView) row.findViewById(R.id.distance);
    fourText.setText(getFormatDistance(values.get(position).distance));

It returns the next error:

01-23 09:45:48.816: E/AndroidRuntime(8677): java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
Yeray
  • 1,265
  • 1
  • 11
  • 23

3 Answers3

3

Use Pattern.quote() to split the string by dot symbol.

Do like this

String[] parts = doubleAsText.split(Pattern.quote("."));

Please see here how to split the double value to Integer part and Fractional part.

Community
  • 1
  • 1
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0
if (CharMatcher.is('.').countIn("doubleAsText") > 1) {
            return doubleAsText;
        } else {
            String[] parts = doubleAsText.split(".");
            String part1 = parts[0];
            String part2 = parts[1];
            //part2 = part2.split("");
            return part2;
        }
Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
0

String.split() uses Regular Expressions, where the Dot . is a special Character. So you need to escape the Dot, so you can split by the character dot and don't use the dot as a special (funcional) character in the regular expression.

String[] parts = s.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
Simulant
  • 19,190
  • 8
  • 63
  • 98
  • Hi, thanks for your answer, but I want separate first the double to integer part and decimal part and now it works well grace to Prabhakaran. However, I need to show only the first three digits of my string param. Thank you for your help. – Yeray Jan 23 '14 at 09:15