How to Convert a String to a Number in Java

The challenge

We need a function that can transform a string into a number. What ways of achieving this do you know?

Note: Don’t worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.

Examples

stringToNumber("1234") == 1234 stringToNumber("605" ) == 605 stringToNumber("1405") == 1405 stringToNumber("-7" ) == -7
Code language: Java (java)

Test cases

import org.junit.Test; import static org.junit.Assert.assertEquals; public class StringToNumberTest { @Test public void test1(){ assertEquals("stringToNumber(1234)", 1234 , StringToNumber.stringToNumber("1234")); } @Test public void test2(){ assertEquals("stringToNumber(605)", 605 , StringToNumber.stringToNumber("605")); } @Test public void test3(){ assertEquals("stringToNumber(1405)", 1405 , StringToNumber.stringToNumber("1405")); } @Test public void test4(){ assertEquals("stringToNumber(-7)", -7 , StringToNumber.stringToNumber("-7")); } @Test public void test5(){ for(int i = 0; i < 100; ++i) { int t = (int)Math.round(Math.random() * 500000); assertEquals("stringToNumber(" + t + ")", t , StringToNumber.stringToNumber(Integer.toString(t))); } } }
Code language: Java (java)

The solution in Java

Option 1 (using parseInt):

public class StringToNumber { public static int stringToNumber(String str) { return Integer.parseInt(str); } }
Code language: Java (java)

Option 2 (using valueOf):

public class StringToNumber { public static int stringToNumber(String str) { return Integer.valueOf(str); } }
Code language: Java (java)

It may be good practice to go a step further and sanity check the output:

public class StringToNumber { public static int stringToNumber(String str) { try { return Integer.parseInt(str); } catch (NumberFormatException NFE) { throw NFE; } } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments