1. 程式人生 > >字串轉整數或浮點數

字串轉整數或浮點數

Java中字串轉整型或浮點數的例子。

程式碼

package test.examples;

public class TestExamples {

    public static void Trans2Int(String str) {
        try {
            int i = Integer.parseInt(str);
            System.out.println("Trans2Int(), i=" + i);
        } catch (Exception e) {
            System.out.println("Trans2Int() Exception:");
            e.printStackTrace();
        }
    }

    public static void Trans2Float(String str) {
        try {
            float f = Float.parseFloat(str);
            System.out.println("Trans2Float(), f=" + f);
        } catch (Exception e) {
            System.out.println("Trans2Float() Exception:");
            e.printStackTrace();
        }
    }

    public static void sleep(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final String[] values = {"123", "123.0"};

        for (String str : values) {
            System.out.println("str: " + str);

            Trans2Int(str);
            sleep(2);

            Trans2Float(str);
            sleep(2);
        }
    }

}

執行結果

str: 123
Trans2Int(), i=123
Trans2Float(), f=123.0
str: 123.0
Trans2Int() Exception:
java.lang.NumberFormatException: For input string: "123.0"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at test.examples.TestExamples.Trans2Int(TestExamples.java:7)
    at test.examples.TestExamples.main(TestExamples.java:39)
Trans2Float(), f=123.0

C/C++的情況

程式碼

#include <cstdio>
#include <cstdlib>

int main()
{
    const char* values[] = {"123", "123.0"};

    int i;
    double f;

    for (size_t index = 0; index < 2; index++) {
        i = -1;
        f = -1.0;

        i = atoi(values[index]);
        f = atof(values[index]);

        printf("str = %s, i = %d, f = %lf\n", values[index], i, f);
    }

    return 0;
}

執行結果

str = 123, i = 123, f = 123.000000
str = 123.0, i = 123, f = 123.000000
請按任意鍵繼續. . .