简体   繁体   中英

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.

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

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

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.

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: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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