> Does anybody know a free available class / lib to parse a dimension
> expressed with inches and fractions to a float value?
> Input e.g. String "24 1/16" -> Output Float 24.0625.
Uh, you can't create one yourself? That isn't a hard problem to solve if
you enforce certain formats for entering the information. You don't even
need a whole library in my opinion.
"24 1/16"
split using a space
"24" and "1/16"
float l = Float.parseFloat("24")
"1/16"
split using /
"1" and "16"
float n = Float.parseFloat("1")
float d = Float.parseFloat("16")
float r = n/d;
float f = l + r;
Frank Langelage - 13 Mar 2007 22:24 GMT
>> Does anybody know a free available class / lib to parse a dimension
>> expressed with inches and fractions to a float value?
[quoted text clipped - 22 lines]
>
> float f = l + r;
I thought this should be a common problem for programmers in North
America and I don't have ro reinvent a solution.
It's not that simple if you want get strings like "1/4" or "5 1/4" or "1".
I got another reply to my question from Dinesh Kapoor. I enhanced his
example to work with this different input:
public class Fractions
{
private double whole;
private double numerator;
private double denominator;
public Fractions( String s )
{
String[] result = s.trim().split( "\\s+" );
String wholePart;
String fractionPart[];
if ( result[0].matches( "\\d+" ) ) {
whole = Double.parseDouble( result[0] );
if ( result.length > 1 ) {
fractionPart = result[1].split( "/" );
} else {
fractionPart = new String[] { "0", "1" };
}
} else {
whole = 0;
fractionPart = result[0].split( "/" );
}
numerator = Double.parseDouble( fractionPart[0] );
denominator = Double.parseDouble( fractionPart[1] );
}
public double toDouble()
{
double temp = whole + ( numerator / denominator );
return temp;
}
public static void main( String[] args )
{
Fractions f = new Fractions( "24 1/16" );
System.out.println( f.toDouble() );
f = new Fractions( "1/4" );
System.out.println( f.toDouble() );
f = new Fractions( "1" );
System.out.println( f.toDouble() );
f = new Fractions( "5 1/4" );
System.out.println( f.toDouble() );
}
}
Joshua Cranmer - 13 Mar 2007 23:21 GMT
>>> Does anybody know a free available class / lib to parse a dimension
>>> expressed with inches and fractions to a float value?
[quoted text clipped - 54 lines]
> denominator = Double.parseDouble( fractionPart[1] );
> }
I prefer simpler regex:
Pattern p = Pattern.compile("(\\d*)\\s*(\\d+)/(\\d+)");
Matcher m = p.match(s);
if (m.matches()) {
whole = Integer.parseInt(m.group(1));
numerator = Integer.parseInt(m.group(2));
denominator = Integer.parseInt(m.group(3));
}