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

1
2
3
4
stringToNumber("1234") == 1234
stringToNumber("605" ) == 605
stringToNumber("1405") == 1405
stringToNumber("-7"  ) == -7

Test cases

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)));
      }
    }
}

The solution in Java

Option 1 (using parseInt):

1
2
3
4
5
6
7
public class StringToNumber {
  public static int stringToNumber(String str) {

    return Integer.parseInt(str);

  }
}

Option 2 (using valueOf):

1
2
3
4
5
6
7
public class StringToNumber {
  public static int stringToNumber(String str) {

    return Integer.valueOf(str);

  }
}

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class StringToNumber {
  public static int stringToNumber(String str) {

    try {

      return Integer.parseInt(str);

    } catch (NumberFormatException NFE) {

      throw NFE;

    }

  }
}