简体   繁体   English

Java,如何将十进制数字作为字符串转换为整数

[英]Java, How to convert decimal number as string into an integer

I have a text file with decimal numbers in it. 我有一个带十进制数字的文本文件。 I am trying to use Integer.valueOf() in a Java program and it does not convert the decimal numbers. 我试图在Java程序中使用Integer.valueOf() ,它不转换十进制数。

How do I convert the decimal number string into an int? 如何将十进制数字串转换为int?

You can use java's Double.valueOf() defined here instead; 您可以使用此处定义的 java的Double.valueOf() ; then you can convert the resulting double to an int. 然后你可以将结果double转换为int。

You can convert string representation of numbers to "numbers" by using the respecive parseX() method. 您可以使用相应的parseX()方法将数字的字符串表示形式转换为“数字”。 For integers that would be Integer.parseInt(), for doubles Double.parseDouble(), for "longs" -> Long.parseLong(), etc. 对于整数,可以是Integer.parseInt(),对于双精度Double.parseDouble(),对于“longs” - > Long.parseLong()等。

PS: If you are using Scanner to read your text file, you can use scanner.nextInt(), to directly read the numbers from the text file! PS:如果您使用Scanner读取文本文件,可以使用scanner.nextInt()直接读取文本文件中的数字!

PS: the variouse parseX() methods return primitives (int, long...), while the valueOf() method returns wrapper classes (Integer, Long...), so you should use the parseX() methods where possible (where you need primitives) in order to avoid unnecessary auto(un)boxing. PS:variouse parseX()方法返回原语(int,long ...),而valueOf()方法返回包装类(Integer,Long ...),所以你应该尽可能使用parseX()方法(其中)你需要原语),以避免不必要的自动(联合)拳击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM