Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent numeric conversion behaviour #9767

Open
scabug opened this issue Apr 27, 2016 · 4 comments
Open

Inconsistent numeric conversion behaviour #9767

scabug opened this issue Apr 27, 2016 · 4 comments
Milestone

Comments

@scabug
Copy link

scabug commented Apr 27, 2016

When converting string to numbers, the behaviour between natural numbers and floating points is different with regard to leading and trailing spaces:

scala> " 1".toInt
  java.lang.NumberFormatException
scala > "1 ".toLong
  java.lang.NumberFormatException
scala> " 1 ".toFloat
  res3: Float = 1.0
scala> " 1 ".toDouble
  res4: Double = 1.0

The documentation is exactly the same in both cases even though the results are not: http://www.scala-lang.org/api/2.11.8/#scala.collection.immutable.WrappedString. Internally, Java's parseInt/Long/Float/Double are used, but perhaps it's a good idea to add a call to trim in the case of integer types. See source: https://github.com/scala/scala/blob/99a82be91cbb85239f70508f6695c6b21fd3558c/src/library/scala/collection/immutable/StringLike.scala

@scabug
Copy link
Author

scabug commented Apr 27, 2016

Imported From: https://issues.scala-lang.org/browse/SI-9767?orig=1
Reporter: Ian Hellstrom (hellstorm)
Affected Versions: 2.11.7

@scabug
Copy link
Author

scabug commented May 15, 2016

Mike Pheasant (intronic) said:
I am happy to provide a fix for this, if required.

  • Should the trim() code be added? Or documentation included explaining the behaviour?

On one hand, the behaviour seems inconsistent and the suggestion sounds reasonable.

On the other hand the behaviour is consistent with the documentation and semantics of the java7 methods.

@scabug
Copy link
Author

scabug commented May 15, 2016

Mike Pheasant (intronic) said:
OK I think its worth doing and I will have a crack at it.

After looking into the Java code, it seems reasonable to add the trim() and make the Scala double/int handling consistent.
It does not seem to add any major performance concerns.
Anyone relying on the java behaviour (not documented in scala) can always call the java parseInt.

Notes from java code:

@scabug
Copy link
Author

scabug commented Jul 16, 2016

@som-snytt said:
Doc and test scala/scala@6083875

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants