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.
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()
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 thestart
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 a0.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.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 for1.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.