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?

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?

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) / Double.parseDouble(rat);
} 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
``````

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.

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.

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

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);
}
else {
return 0d;
}
}
double b = Double.parseDouble(fractionArray);
if (b==0d){
return 0d;
}
Double a = Double.parseDouble(fractionArray);
return a/b;
}
catch (NumberFormatException e){
return 0d;
}
}
``````

``````SpannableStringBuilder test = new SpannableStringBuilder();