Expecting strings like "2 1/2". compute to total amount compounding all the components (splitting the original string on the blank space) - Java java.lang

Java examples for java.lang:double Format

Description

Expecting strings like "2 1/2". compute to total amount compounding all the components (splitting the original string on the blank space)

Demo Code


//package com.java2s;

public class Main {

    /**/*from  ww w. j  a  v a 2  s . com*/
     * Expecting strings like "2 1/2". The method will compute to total amount compounding all
     * the components (splitting the original string on the blank space).
     *
     * @param amount a string representing a complex number that needs to be compounded (e.g. "2 1/2")
     * @return a parsed number
     */
    public static double parseComplexAmountsWithSpacesAndFractions(
            String amount) {
        String[] amounts = amount.split(" ");
        double compundedAmount = 0;
        for (String currentAmount : amounts) {
            compundedAmount += parseFraction(currentAmount);
        }

        return compundedAmount;
    }

    /**
     * Expecting strings like "1/2" or "2/3" etc.
     * The method provides a double type representing the input string as a number.
     *
     * @param ratio a string representing a ratio (fraction)
     * @return a parsed number
     */
    public static double parseFraction(String ratio) {

        if (ratio.contains("/")) {
            String[] rat = ratio.split("/");
            return Double.parseDouble(rat[0]) / Double.parseDouble(rat[1]);
        } else {
            return Double.parseDouble(ratio);
        }
    }
}

Related Tutorials