简体   繁体   中英

Write code to convert string value of “1 1/2” to Double 1.5

This is the sample code I came up with, is there a better way to do this without having to use any external jars. The method convertStringToDouble is the main method that does the conversion. Also restricting the decimal value to 2 digits after the period.

import java.text.DecimalFormat;

public class ExampleCode {

    private final static String ROUND_DECIMAL_VALUE = "#.##";

    public static void main(String[] args) {

    String s = "1 1/2";

      Double dd =  convertStringToDouble(s);
        System.out.println("***Final converted value***" +dd);
    }


    /**
     * Convert the String dose value to Double
     *
     * @param dose
     * @return finalDoseVal
     */
    private static Double convertStringToDouble(String dose) {

        Double finalDoseVal = null;

        if(dose != null && !dose.isEmpty()) {
            if (dose.contains("/")) {

                String[] splitStr = dose.split(" ");

                DecimalFormat df2 = new DecimalFormat(ROUND_DECIMAL_VALUE);

                if (splitStr.length == 2) {

                    String wholeNum = splitStr[0];
                    String fractionValue = splitStr[1];

                    Double fractionValToDouble = parseFractionalValue(fractionValue);

                    finalDoseVal = Double.sum(Double.valueOf(wholeNum), Double.valueOf(df2.format(fractionValToDouble)));

                } else if (splitStr.length == 1) {
                    String numOrFractionValue = splitStr[0];
                    Double d;
                    if (numOrFractionValue.contains("/")) {
                        d = Double.valueOf(df2.format(parseFractionalValue(numOrFractionValue)));
                    } else {
                        d = Double.valueOf(numOrFractionValue);
                    }
                    finalDoseVal = d;
                }
            }
            else {
                if(dose != null && !dose.isEmpty()) {
                    finalDoseVal = Double.valueOf(dose);
                }
            }
        }
        return finalDoseVal;
    }

This is the method that converts the fractional String value to a decimal.

/**
 * Convert fractional String value to decimal value
 * e.g "1/2" converted to 0.5
 *
 * @param ratio
 * @return Double
 */
public static double parseFractionalValue(String ratio) {
    if (ratio.contains("/")) {
        String[] rat = ratio.split("/");
        return Double.parseDouble(rat[0]) / Double.parseDouble(rat[1]);
    } else {
        return Double.parseDouble(ratio);
    }
}

Made sure to add a trim onto there so spaces around the edges don't make it flip out. Anyways, it's pretty simple overall. You just have to split it twice, once for the slash, and once for the space. Once you've done that, you just parse them, and then for the rounding I like to use the round function. If you multiply by 100 inside of the round function and divide by 100 outside of it, it'll give you two decimal places.

private static double StringtoDouble(String dose){

  if(dose!=null&&dose.length()>0){
    if(dose.contains("/")){
      String[] inter = dose.trim().split("/");
      if(inter[0].contains(" ")){
        String[] inter2 = inter[0].split(" ");
        return (double)round((Float.parseFloat(inter2[0])+Float.parseFloat(inter2[1])/Float.parseFloat(inter[1]))*100)/100;
      } else {
        return (double)floor((Float.parseFloat(inter[0])/Float.parseFloat(inter[1]))*100)/100;
      }
    } else {
      return (double)floor((Float.parseFloat(dose))*100)/100;
    }
  } else { 
    return 0;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM