2012-12-29 43 views
1

我想在Java中將字符串轉換爲數字。我已經嘗試過兩種方法,但都用整數工作不好,增加了一個不需要的浮點:「1」> 1.0(當我想要「1」> 1和「1.5」> 1.5)。我發現了幾種將字符串轉換爲數字的方法,但它們或者不工作,或者很多行很長,我不能相信它是如此複雜的來自JavaScript,我只需要parseFloat()。Java將字符串轉換爲數字,僅在需要時才浮點數?

這是我現在想:

String numString = "1".trim().replaceAll(",",""); 
float num = (Float.valueOf(numString)).floatValue(); // First try 
Double num2 = Double.parseDouble(numString); // Second try 
System.out.println(num + " - " + num2); // returns 1.0 - 1.0 

怎樣纔可以有需要,只有當浮點?

+1

爲什麼不使用Integer.parseInt(numString);? –

+1

@ Priyanka.Patil因爲含義是其中一個數字將是1.5(輸出 - >「1.5」)。 – 2012-12-29 19:45:53

+0

請首先考慮您的問題「如何才能在需要時獲得浮點數?」這就是問題所在,並閱讀下面的答案。提示「有」,如「在屏幕上打印」或「在變量中存儲」? –

回答

3

要格式化如你所願的浮動,使用DecimalFormat

DecimalFormat df = new DecimalFormat("#.###"); 
System.out.println(df.format(1.0f)); // prints 1 
System.out.println(df.format(1.5f)); // prints 1.5 

在你的情況,你可以使用

System.out.println(df.format(num) + " - " + df.format(num2)); 
1

我想你要找的是什麼DecimalFormat

DecimalFormat format = new DecimalFormat("#.##"); 
double doubleFromTextField = Double.parseDouble(myField.getText()); 
System.out.println(format.format(doubleFromTextField)); 
0

問題出在你的問題真的是一個類型安全的語言,我認爲你在混合轉換和字符串表示。在Java或C#或C++中,您將轉換爲某種可預測/預期的類型,看起來像您期待在JavaScript中習慣的「變體」行爲。

什麼,你可以在一個類型安全的語言做到這一點:

public static Object convert(String val) 
{ 
    // try to convert to int and if u could then return Integer 
    ELSE 
    //try to convert to float and if you could then return it 
    ELSE 
    //try to convert to double 
    etc... 
} 

當然這只是如JavaScript相比於C++或Java的效率非常低。然後你可以做toString()來獲得格式爲整數的整數,float類型爲float,double類型爲double,多態的。但是,你的問題最多隻能含糊不清,導致我認爲存在概念問題。