Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>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 &lt; 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; } </code></pre> <p>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. </p> <p>This is how my code works.</p> <p>First it checks the sign at the first character <code>[0]</code> then increments the <code>start</code> position to 1 instead of zero to start the loop past the <code>-</code> sign. </p> <p>It loops through the array and checks to see if there is a <code>.</code> 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 <code>0.0</code> 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.</p> <pre><code>value += (a.charAt(i) - 48) * Math.pow(10,a.length() - i - 1); </code></pre> <p>this line of code is very interesting. <code>a.charAt(i) - 48</code> 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 <code>1.0</code>). Then i add it value.</p> <p>Everything else is pretty self explanatory. </p> <p><strong>NOTE:</strong></p> <p>I tested this code myself, however one important thing is that i haven't added checks for invalid strings with other characters. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload