Java Franction Convert fractionToDecimal(String fraction)

Here you can find the source of fractionToDecimal(String fraction)

Description

Converts a String fraction into a double value.

License

Apache License

Parameter

Parameter Description
fraction the String to convert to a fraction

Return

the double value of the fraction, 0 if null, or an exception if not a number

Declaration

public static double fractionToDecimal(String fraction) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  w w  w.j  a  va 2s .  c  o m*/
     * Converts a String fraction into a double value. Nulls are allowed. If the given String is null, 0 will be returned.
     * <p>
     * An <tt>IllegalArgumentException</tt> will be thrown if the denominator is 0.
     * <p>
     * A <tt>NumberFormatException</tt> will be thrown if any part of the String can not be formatted as a number.
     * 
     * @param fraction
     *          the String to convert to a fraction
     * @return the double value of the fraction, 0 if null, or an exception if not a number
     */
    public static double fractionToDecimal(String fraction) {
        if (fraction == null || "".equals(fraction)) {
            throw new NumberFormatException(
                    "A null or empty String can not be converted to a fraction.");
        }

        String[] split = fraction.split("/");
        if (split.length == 1) {
            return Double.valueOf(fraction);
        } else if (split.length == 2) {
            String numerator = split[0];
            String denominator = split[1];
            split = numerator.split("\\s");
            double wholeNumber = 0;
            if (split.length == 2) {
                wholeNumber = Double.valueOf(split[0]);
                numerator = split[1];
            }
            double n = Double.valueOf(numerator);
            double d = Double.valueOf(denominator);
            if (d == 0) {
                throw new IllegalArgumentException(
                        "Argument 'divisor' is 0");
            }
            double decimal = n / d;
            return wholeNumber + decimal;
        }
        throw new NumberFormatException(
                "The given string can not be converted to a fraction: "
                        + fraction);
    }
}

Related

  1. fractionAlongRay(double px, double py, double qx, double qy, double rx, double ry)
  2. fractionalPart(float fnum)
  3. fractionalTime(int hour, int minute, int second)
  4. fractionDigits(double number)
  5. fractionOfStringUppercase(String input)