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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16566149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:19:13  来源:igfitidea点击:

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

javastringinteger

提问by jdg

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.

我有一个带有十进制数字的文本文件。我正在尝试Integer.valueOf()在 Java 程序中使用它,但它不转换十进制数。

How do I convert the decimal number string into an int?

如何将十进制数字字符串转换为 int?

回答by Bathsheba

You can use java's Double.valueOf()defined hereinstead; then you can convert the resulting double to an int.

您可以使用Double.valueOf()此处定义的java代替;然后您可以将结果双精度转换为整数。

回答by Svetlin Zarev

You can convert string representation of numbers to "numbers" by using the respecive parseX() method. For integers that would be Integer.parseInt(), for doubles Double.parseDouble(), for "longs" -> Long.parseLong(), etc.

您可以使用相应的 parseX() 方法将数字的字符串表示形式转换为“数字”。对于整数,将是 Integer.parseInt(),对于双精度 Double.parseDouble(),对于“longs”-> Long.parseLong() 等。

PS: If you are using Scannerto 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:各种 parseX() 方法返回原语(int、long...),而 valueOf() 方法返回包装类(Integer、Long...),因此您应该尽可能使用 parseX() 方法(其中您需要原语)以避免不必要的自动(取消)装箱。