Sunday 23 October 2016

Learn more on Scala Types : Parsing a Number from a String : Day 3 Learnings

You want to convert a String to one of Scala’s numeric types:

Use the to* methods that are available on a String (courtesy of the StringLike trait):

scala> "100".toInt
res0: Int = 100

scala> "100".toDouble
res1: Double = 100.0

scala> "100".toFloat
res2: Float = 100.0

scala> "1".toLong
res3: Long = 1

scala> "1".toShort
res4: Short = 1

scala> "1".toByte
res5: Byte = 1

Be careful, because these methods can throw the usual Java NumberFormatException :

scala> "foo".toInt
java.lang.NumberFormatException: For input string: "foo"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java)
at java.lang.Integer.parseInt(Integer.java:449)
... more output here ...

BigInt and BigDecimal instances can also be created directly from strings (and can also throw a NumberFormatException ):

scala> val b = BigInt("1")
b: scala.math.BigInt = 1

scala> val b = BigDecimal("3.14159")
b: scala.math.BigDecimal = 3.14159


Handling a base and radix

If you need to perform calculations using bases other than 10 , you’ll find the toInt method in the Scala Int class doesn’t have a method that lets you pass in a base and radix

To solve this problem, use the parseInt method in the java.lang.Integer class, as shown in these examples:

scala> Integer.parseInt("1", 2)
res0: Int = 1

scala> Integer.parseInt("10", 2)
res1: Int = 2

scala> Integer.parseInt("100", 2)
res2: Int = 4

scala> Integer.parseInt("1", 8)
res3: Int = 1

scala> Integer.parseInt("10", 8)
res4: Int = 8


Implicit conversions

If you’re a fan of implicit conversions, you can create an implicit class and method to help solve the problem.

Add Your Own Methods to the String Class” create the implicit conversion as follows:

implicit class StringToInt(s: String) {
 def toInt(radix: Int) = Integer.parseInt(s, radix)
}

Defining this implicit class (and bringing it into scope) adds a toInt method that takes a radix argument to the String class, which you can now call instead of calling Integer.parseInt :

scala> implicit class StringToInt(s: String) {
        |  def toInt(radix: Int) = Integer.parseInt(s, radix)
        | }
defined class StringToInt

scala> "1".toInt(2)
res0: Int = 1

scala> "10".toInt(2)
res1: Int = 2

scala> "100".toInt(2)
res2: Int = 4

scala> "100".toInt(8)
res3: Int = 64

scala> "100".toInt(16)
res4: Int = 256








Share this article with your friends.

No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...