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

Try to convert string value in Double/Float decoders #173

Closed
knutwalker opened this issue Jan 25, 2016 · 2 comments
Closed

Try to convert string value in Double/Float decoders #173

knutwalker opened this issue Jan 25, 2016 · 2 comments

Comments

@knutwalker
Copy link

From the Gitter conversation.

The Decoders for Int, Long and other integral types try to convert a string into their number type.

import io.circe._, parse._, cats.data.Xor
scala> val Xor.Right(i) = decode[Int]("\"42\"")
i: Int = 42

The decoder for Double and Float don't try this conversion because of this:

scala> "Infinity".toDouble
res1: Double = Infinity

However, we could use JsonNumber.fromString and _.toDouble to try to safely convert a String into a Double, for example:

scala> val doubleWithFromString = Decoder.instance(c => c.as[String].flatMap(s => Xor.fromOption(JsonNumber.fromString(s).map(_.toDouble), DecodingFailure("Double", c.history))))
doubleWithFromString: io.circe.Decoder[Double] = io.circe.Decoder$$anon$8@47016c8b

scala> val Xor.Right(d) = decode("\"13.37\"")(doubleWithFromString)
d: Double = 13.37

scala> val Xor.Left(e) = decode("\"Infinity\"")(doubleWithFromString)
e: io.circe.Error = io.circe.DecodingFailure: Double

scala> val Xor.Left(e) = decode("\"NaN\"")(doubleWithFromString)
e: io.circe.Error = io.circe.DecodingFailure: Double

If "Infinty" and "NaN" are valid to be parsed as Double, one can fallback to using a Decoder[String].map(_.toDouble) approach.

@MartinSeeler
Copy link

I think this is a good idea!

@travisbrown
Copy link
Member

Fixed in #189.

julienrf pushed a commit to scalacenter/circe that referenced this issue May 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants