Here you can find the source of fractionToDecimal(String fraction)
Parameter | Description |
---|---|
fraction | the String to convert to a fraction |
public static double fractionToDecimal(String fraction)
//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); } }