Expecting strings like "1/2" or "2/3" etc. this method provides a double type representing the input string as a number - Java java.lang

Java examples for java.lang:double Format

Description

Expecting strings like "1/2" or "2/3" etc. this method provides a double type representing the input string as a number

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String ratio = "java2s.com";
        System.out.println(parseFraction(ratio));
    }/*  w  w w  .  j a  v  a 2s  . c om*/

    /**
     * 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