Home » Android » android – How to convert from fraction formatted string to Decimal or Float in Java?

android – How to convert from fraction formatted string to Decimal or Float in Java?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have few string values which I am fetching from my database e.g

"1/4","2/3"

But while displaying as Android ListView contents I need to display it as 0.25,0.66.

Now I don’t want to split the string and then covert to individual strings to numbers and
then divide them to have result.

Does anyone know, any direct functions like Double.valueOf or parseDouble kind?

How to&Answers:

Why you “dont want to split the string and then covert to individual strings to numbers and then divide them to have result”?

I am not aware of any built-in function to do that so the simplest solution:

double parse(String ratio) {
    if (ratio.contains("/")) {
        String[] rat = ratio.split("/");
        return Double.parseDouble(rat[0]) / Double.parseDouble(rat[1]);
    } else {
        return Double.parseDouble(ratio);
    }
}

It also covers the case where you have integer representation of ratio

parse("1/2") => 0.5
parse("3/7") => 0.42857142857142855
parse("1") => 1.0

Answer:

I imagine you have solved this problem in the last 2 years; however, you can use the Apache commons fraction class.

It has a built in parser, so if you were to call:

Fraction fraction = Fraction.getFraction("1/2");
double d = fraction.doubleValue();

Then d should contain .5.

Answer:

You can split the fraction using split("/"). Then you can convert the values to Double and perform the division. I have no idea of Android, that’s how I’d do it in Java.

Answer:

In java, we don’t have anything like the eval from JavaScript so you could possibly use this.

Answer:

I don’t think that there is anything like that. But I don’t see why you wouldn’t create your own function like this:

public static double fromStringFraction(String fraction){
    String[] fractionArray = fraction.split("/");
    try {
        if (fractionArray.length != 2){
            if (fractionArray.length == 1){
                return Double.parseDouble(fractionArray[0]);
            }
            else {
                return 0d;
            }
        }
        double b = Double.parseDouble(fractionArray[1]);
        if (b==0d){
            return 0d;
        }
        Double a = Double.parseDouble(fractionArray[0]);
        return a/b;
    }
    catch (NumberFormatException e){
        return 0d;
    }
}

Answer:

try using

SpannableStringBuilder test = new SpannableStringBuilder();
test.append("\n");
test.append(Html.fromHtml("<sup>5</sup>/<sub>9</sub>"));
test.append("\n");