String-Double not working for negative numbers

2020-08-01 01:57发布

public class Convert{
    public static void main(String args[]){
        String num="-12.0";
        int g=0,fnl=0;
        int exp=(num.indexOf(".")-1);
        String num2=num;
        if(num.charAt(0)==('-')){
            num=num.substring(1);
            System.out.println(num);
        }
        String numb=num;
        System.out.println(numb);
        int d=0;
        while(numb.charAt(d)!='.'){
                g=numb.charAt(d)-48;
                System.out.println(g);
                int k = 1;
                for(int f=0;f<exp;f++){
                k=(k*10);
                }
                fnl+=(k*g);
                d++;
                exp--;
                System.out.println(fnl);

        }

        num=(num.substring(d) );

         double num1= Double.parseDouble(num); 
         double finalnum=(fnl+num1);
         System.out.println(fnl);
         if(num2.charAt(0)=='-'){
             finalnum*=-1;
         }

    }
}

I created my own method to convert the integer part of the string and it's only working for positive numbers. :( It should work for both positive and negative numbers. and I used parse double to convert the numbers after the decimal point. I cant use parse double to convert the whole string to double because we're not allowed to do so.

标签: java
3条回答
贪生不怕死
2楼-- · 2020-08-01 02:12
int g=0,fnl=0;
String input  = "-12.0";
String temp = input;
String forDecimalPart = input;
if(input.charAt(0)=='-') {
    temp=input.substring(1);
}

int exp = temp.indexOf(".");
System.out.println(exp);
int d=0;
while(temp.charAt(d)!='.') {
    g=temp.charAt(d)-48;
    int k = 1;
    for(int f=1;f<exp;f++) {
      k*=10;
    }
    fnl+=(k*g);
    d++;
    exp--;
    System.out.println(fnl);
}

forDecimalPart=temp.substring(d) ;

double num1= Double.parseDouble(forDecimalPart); 
double finalnum=(fnl+num1);
if(input.charAt(0)=='-'){
finalnum*=-1;
}
System.out.println(finalnum);

i have given you the answer as you have put the effort to come up with atleast this code. good luck :) I have scripted the code resembling your question without adding any Extra methods from other classes like Math.pow()

查看更多
三岁会撩人
3楼-- · 2020-08-01 02:17
public static double toDouble(String a){
     int sign = 1;
     int start = 0;
     if(a.charAt(0) == '-'){
         start = 1;
         sign = -1;
     }
     double value = 0;
     boolean decimal = false;
     int exp = 0;

     for(int i = start; i < a.length(); i++){
         if(a.charAt(i) == '.'){
             if(decimal) return 0.0;
             decimal = true;
         }else{
             value += (a.charAt(i) - 48) * Math.pow(10,a.length() - i - 1);
         }

         if(decimal) exp++;
     }

     value =  value / Math.pow(10,exp);
     value *= sign;
      System.out.println(value);
     return value;

 }

I sort of rewrote it the way i would do this problem. If you remember i posted psuedo code on your other question this is my "programmed" version.

This is how my code works.

First it checks the sign at the first character [0] then increments the start position to 1 instead of zero to start the loop past the - sign.

It loops through the array and checks to see if there is a . if it is it sets the decimal variable to true instead of false. If it reads more than one decimal point in the string it will return a 0.0 which i denoted as a fail value. However, if it doesn't pick up anymore decimals it increments the exponent value to see how many spaces it will need to jump.

value += (a.charAt(i) - 48) * Math.pow(10,a.length() - i - 1);

this line of code is very interesting. a.charAt(i) - 48 converts the character to an integer value. then i multiply it by 10^(what power of ten the value is at then subtract one to compensate for 1.0). Then i add it value.

Everything else is pretty self explanatory.

NOTE:

I tested this code myself, however one important thing is that i haven't added checks for invalid strings with other characters.

查看更多
放我归山
4楼-- · 2020-08-01 02:26
import java.util.regex.*;

public class DoubleParse{

public static void main(String[] args)
{

    String[] doubles = "12.3 4.08 5 -5 -5.4 4.0 0 0.0 5.800 asda".split(" ");
    for (String num: doubles)
    {
        System.out.println(parse_double(num));
    }
}


final static Pattern double_format = Pattern.compile("^(\\-?)[0]*([0-9]+)(?:\\.([0-9]+?)[0]*)?$");


public static double parse_double(String num)
{

    Matcher m = double_format.matcher(num);
    if (!m.matches())
        throw new IllegalArgumentException(num+" is not in proper format!");

    int sign = num.charAt(0)=='-'? -1 : 1;
    int point = num.indexOf('.');
    int whole = parse_int(num.substring(sign==-1? 1 : 0, (point!=-1)? point : num.length()));
    double fraction=0;
    if (point != -1)
    {
        String fractionS = num.substring(point+1);
        fraction = parse_int( fractionS)/Math.pow(10, fractionS.length());
    }
    return (whole+fraction)*sign;
}

public static int parse_int(String numS)
{
    int num=0;
    for (int i=0;i<numS.length();i++)
    {
        num *= 10;
        num += (int) (numS.charAt(i)-'0');
    }
    return num;
}
}
查看更多
登录 后发表回答