How to convert from a formatted string of phrases to decimal or float in Java?

I have some string values ​​that I retrieve from my database, for example

"1/4","2/3" 

But while you are showing the contents of the Android ListView, I need to display it as 0.25 , 0.66 .

Now I don’t want to break the line and then hide the individual lines into numbers and then divide them by the result.

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

+7
source share
6 answers

Why don't you "want to split the string and then hide the individual strings into numbers and then divide them by the result"?

I don't know any built-in function to do this, so the simplest solution is:

 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 an integer representation of a relationship

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

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

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

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

Then d must contain .5.

+3
source

You can split fractions using split("/") . You can then convert the values ​​to Double and do the division. I have no idea about Android that I would do this in Java.

+1
source

In java, we have nothing like eval from JavaScript, so you can use this .

+1
source

I don’t think there is anything like that. But I do not understand why you would not create your own function as follows:

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

try using

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

All Articles