TechnoGeezer
TechnoGeezer

Reputation: 197

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

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?

Upvotes: 9

Views: 15346

Answers (6)

Cameron Stearns
Cameron Stearns

Reputation: 81

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.

Upvotes: 8

gabga
gabga

Reputation: 178

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

Upvotes: 0

Antrromet
Antrromet

Reputation: 15414

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

Upvotes: 1

mishadoff
mishadoff

Reputation: 10789

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

Upvotes: 10

jmrodrigg
jmrodrigg

Reputation: 600

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.

Upvotes: 1

Devangi Desai
Devangi Desai

Reputation: 1383

try using

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

Upvotes: -1

Related Questions