Share this page 

Convert a fraction to a DoubleTag(s): String/Number


import java.math.BigDecimal;
import java.math.MathContext;
import java.text.ParseException;

public class NumberUtils {

  private NumberUtils() {}

  public static Double fractionToDouble(String fraction)
      throws ParseException {
    Double d = null;
    if (fraction != null) {
      if (fraction.contains("/")) {
        String[] numbers = fraction.split("/");
        if (numbers.length == 2) {
          BigDecimal d1 = BigDecimal.valueOf(Double.valueOf(numbers[0]));
          BigDecimal d2 = BigDecimal.valueOf(Double.valueOf(numbers[1]));
          BigDecimal response = d1.divide(d2, MathContext.DECIMAL128);
          d = response.doubleValue();
        }
      }
      else {
        d = Double.valueOf(fraction);
      }
    }
    if (d == null) {
      throw new ParseException(fraction, 0);
    }
    return d;
  }

  public static void main(String[] args) throws Exception{
    System.out.println(NumberUtils.fractionToDouble("1/2"));
    System.out.println(NumberUtils.fractionToDouble("2/3"));
    System.out.println(NumberUtils.fractionToDouble("4/6"));
    System.out.println(NumberUtils.fractionToDouble("4/5"));
    System.out.println(NumberUtils.fractionToDouble("3/9"));

    /*
     * 0.5
     * 0.6666666666666666
     * 0.6666666666666666
     * 0.8
     * 0.3333333333333333
     */
  }
}