[英]Integer.parseInt and string format with decimal number
我嘗試將字符串值轉換為int。 字符串值包含一個十進制數字,但我無法將此值轉換為int格式。
我寫了這段代碼:
public static void main(final String[] args){
System.out.println("Test");
final String nombre = "3.0";
int entier;
entier=Integer.parseInt(nombre);
try
{
System.out.println("result :" + Integer.parseInt(nombre));
}
catch(final NumberFormatException nfe){
System.out.println("NumberFormatException: "+nfe.getMessage());
}
}
我沒有結果 預先感謝您的幫助:)
由於它是字符串中的浮點數,因此請使用Float.parseFloat
或Double.parseDouble
而不是Integer.parseInt
您的String
是Double
而不是Integer
。
try
{
System.out.println("result :" + Float.parseFloat(nombre));
// OR
System.out.println("result :" + Double.parseDouble(nombre));
}
根據您的描述,我知道您要打印一個int。 您可以這樣編碼:
public static void main(final String[] args) throws ParseException {
NumberFormat formatter = NumberFormat.getInstance();
formatter.setParseIntegerOnly(true);
System.out.println("Test");
final String nombre = "3.0";
int entier;
entier=formatter.parse(nombre).intValue();
System.out.println("result :" + entier);
}
NumberFormat將完成這項工作
您仍然可以使用相同的輸入。 嘗試
System.out.println("result :" + new Double(nombre).intValue());
我不確定您要在這里做什么,但這是代碼的一部分:
public static void main(final String[] args){
System.out.println("Test");
final String nombre = "3.0";
float entier;
entier=Float.parseFloat(nombre);
try
{
System.out.println("result :" + Float.parseFloat(nombre));
}
catch(final NumberFormatException nfe){
System.out.println("NumberFormatException: "+nfe.getMessage());
}
}
底線:使用Float.parseFloat或Double.parseDouble
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.