不使用parse double手动将字符串转换为double java

时间:2013-09-13 13:48:36

标签: java

我们被告知在不使用parse double或任何math,int或double函数的情况下将字符串转换为double。我很难用指数转换数字。

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

            }

        }
    }

这些代码只转换给定字符串的int部分,并打印错误的答案。

4 个答案:

答案 0 :(得分:2)

你可以拆分'。',然后循环通过左侧,抓住下一个char数字,如果现有值&gt; 0,将其乘以10,然后添加读数字(使用开关/情况)。你最终会把数字增加到左边。

然后处理'。'的右侧。从右到左做同样的事情,除了这个时间除以10并加上数字/ 10。你会将小数增加到右边。

最后,在左侧将其添加到右侧。

答案 1 :(得分:1)

我建议您逐步调试调试器中的代码,看看它到底在做什么。但是我可以看到

k=(k*10)*g;

应该是

k=k*10 + g;

并且k应该是long,它位于循环之外。

您也不需要使用indexOf。

您需要编写一个读取整数的循环。您不需要拆分字符串。或做任何特别的事,只记得它在哪里。当你完成时,除以10 ^ count。

这是我写的方法

@Override
public double parseDouble() {
    long value = 0;
    int exp = 0;
    boolean negative = false;
    int decimalPlaces = Integer.MIN_VALUE;
    while (true) {
        byte ch = readByte();
        if (ch >= '0' && ch <= '9') {
            while (value >= MAX_VALUE_DIVIDE_10) {
                value >>>= 1;
                exp++;
            }
            value = value * 10 + (ch - '0');
            decimalPlaces++;
        } else if (ch == '-') {
            negative = true;
        } else if (ch == '.') {
            decimalPlaces = 0;
        } else {
            break;
        }
    }

    return asDouble(value, exp, negative, decimalPlaces);
}

此课程https://github.com/OpenHFT/Java-Lang/blob/master/lang/src/main/java/net/openhft/lang/io/AbstractBytes.java

注意:这不会处理e或十六进制p表示法。

答案 2 :(得分:0)

这是oracle如何做到的:)

http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)

final String Digits     = "(\\p{Digit}+)";
final String HexDigits  = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally 
// signed decimal integer.
final String Exp        = "[eE][+-]?"+Digits;
final String fpRegex    =
            ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
             "[+-]?(" + // Optional sign character
             "NaN|" +           // "NaN" string
             "Infinity|" +      // "Infinity" string

// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
// 
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd 
// edition, section 3.10.2.

// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
             "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

// . Digits ExponentPart_opt FloatTypeSuffix_opt
             "(\\.("+Digits+")("+Exp+")?)|"+

// Hexadecimal strings
       "((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "(\\.)?)|" +

// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

        ")[pP][+-]?" + Digits + "))" +
             "[fFdD]?))" +
             "[\\x00-\\x20]*");// Optional trailing "whitespace"

if (Pattern.matches(fpRegex, myString))
    Double.valueOf(myString); // Will not throw NumberFormatException
else
{
    // Perform suitable alternative action
}

如果你想要你可以看看其他的正则表达式模式,那就有很多。

编辑:

模式的漂亮版本:)

private static final Pattern DOUBLE_PATTERN = Pattern
        .compile("[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)"
            + "|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)"
            + "?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");

答案 3 :(得分:0)

这只是一个解决问题的练习,因此不会真正手动完成。更有可能在面试时被问到。因此,正如上面的CodeChimp所解释的那样,最好的方法是使用良好的旧单位,数十,数百,并在整数侧乘以并在小数侧除。

Table EQUIPMENT
+------------------+----------------+
| ID               | AUTO_INCREMENT |
+------------------+----------------+
| NAME             | VARCHAR        |
+------------------+----------------+
| SERIAL_NUMBER    | VARCHAR        |
+------------------+----------------+
| DATE_PURCHASED   | DATE           |
+------------------+----------------+
| DATE_INSTALLED   | DATE           |
+------------------+----------------+
| DATE_UNINSTALLED | DATE           |
+------------------+----------------+

Table TASKS
+------------------------+----------------+
| ID                     | AUTO_INCREMENT |
+------------------------+----------------+
| NAME                   | VARCHAR        |
+------------------------+----------------+
| anything else you need |  ......        |
+------------------------+----------------+

Table TASK_PLAN
+--------------------+------------------------------------------------------------+
| ID                 | AUTO_INCREMENT                                             |
+--------------------+------------------------------------------------------------+
| EQUIPMENT_ID       | foreign key into table EQUIPMENT                           |
+--------------------+------------------------------------------------------------+
| TASK_ID            | foreign key into table TASKS                               |
+--------------------+------------------------------------------------------------+
| MAINTENANCE_PERIOD | INT - number of days between each maintenance of this type |
+--------------------+------------------------------------------------------------+

Table SCHEDULES
+--------------+----------------------------------+
| PLAN_ID      | foreign key into table TASK_PLAN |
+--------------+----------------------------------+
| PLANNED_DATE | DATE                             |
+--------------+----------------------------------+
| STAFF_ID     | foreign key into table EMPLOYEES |
+--------------+----------------------------------+
| RESULT       | BOOLEAN                          |
+--------------+----------------------------------+