user12521913
user12521913

Reputation:

Convert from Int to char -> string -> double -> int

I am new in scala and I am currently doing my self study with a "Learning Scala" book, I have come across a question on

" Convert the number 128 to char , string , double and then back to int. Do you expect the original amount to be retained? Do you need any special conversion functions for this ? "

What I did at first,

val number:Int = 128 
val convertNumberToChar = number.toChar
//Whenever I cast it to char , I will receive '?'

I did my online research but I am still unfamiliar in scala , why am I receiving "?"

I have also come with another solution to retained the value , by converting number to list then to string. But I am unsure if I am doing it right . Do let me your opinion.

val number:Int = 128
val convertToChar = number.toList //This will convert a list of char
val convertToString = convertToChar.mkString //This will convert from list to string 
val convertToDouble = convertToString.toDouble //This will convert to Double
val convertToInt = convertToDouble .toInt // This will convert back to int

Thank you in adance . :)

Upvotes: 1

Views: 679

Answers (1)

jwvh
jwvh

Reputation: 51271

128 isn't the value of a printable character. You're getting ? because the display wants to show you that there is a Char value there but it can't show you the character that the value represents.

Since it is a character (even if it is unshowable), it can be turned into a String of length 1. But that String cannot be turned into a number because only number representations (like "3.56" or "-79") can be converted to a number.

scala> 128.toChar.toString.toDouble.toInt
java.lang.NumberFormatException: For input string: ""
  at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
  at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
  at java.base/java.lang.Double.parseDouble(Double.java:543)
  at scala.collection.immutable.StringLike.toDouble(StringLike.scala:317)
  at scala.collection.immutable.StringLike.toDouble$(StringLike.scala:317)
  at scala.collection.immutable.StringOps.toDouble(StringOps.scala:29)
  ... 28 elided

scala> 55.toChar.toString.toDouble.toInt
res33: Int = 7

In order to restore the original value it has to be transitioned to a type with a different toString method.

scala> 128.toChar.toShort.toString.toDouble.toInt
res34: Int = 128

Upvotes: 2

Related Questions