Yeray
Yeray

Reputation: 1265

Format a String Variable in Android

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

Upvotes: 2

Views: 181

Answers (3)

Simulant
Simulant

Reputation: 20102

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];

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

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.

Upvotes: 3

Digvesh Patel
Digvesh Patel

Reputation: 6533

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

Upvotes: 0

Related Questions