Skip to content

Commit

Permalink
#68: properly detect if a number if a float or int
Browse files Browse the repository at this point in the history
(cherry picked from commit ec4c896)
  • Loading branch information
adamw authored and travisbrown committed Dec 18, 2019
1 parent c388d07 commit 449fe8e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
13 changes: 6 additions & 7 deletions src/main/scala/io/circe/yaml/Printer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,8 @@ final case class Printer(
scalarNode(Tag.NULL, "null"),
bool =>
scalarNode(Tag.BOOL, bool.toString),
number => {
if (number.toLong.nonEmpty)
scalarNode(Tag.INT, number.toString)
else
scalarNode(Tag.FLOAT, number.toString)
},
number =>
scalarNode(numberTag(number), number.toString),
str =>
stringNode(str),
arr =>
Expand Down Expand Up @@ -158,9 +154,12 @@ object Printer {
private def yamlTag(json: Json) = json.fold(
Tag.NULL,
_ => Tag.BOOL,
number => if (number.toLong.nonEmpty) Tag.INT else Tag.FLOAT,
number => numberTag(number),
_ => Tag.STR,
_ => Tag.SEQ,
_ => Tag.MAP
)

private def numberTag(number: JsonNumber): Tag =
if (number.toString.contains(".")) Tag.FLOAT else Tag.INT
}
7 changes: 6 additions & 1 deletion src/test/scala/io/circe/yaml/PrinterTests.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package io.circe.yaml

import io.circe.Json
import io.circe.{Json, JsonNumber}
import io.circe.yaml.Printer.{FlowStyle, LineBreak, StringStyle, YamlVersion}
import org.scalatest.{FreeSpec, Matchers}

Expand Down Expand Up @@ -102,6 +102,11 @@ class PrinterTests extends FreeSpec with Matchers {
Printer.spaces2.pretty(json) shouldEqual "22.22\n"
}

"Root float without decimal part" in {
val json = Json.fromDoubleOrNull(22.0)
Printer.spaces2.pretty(json) shouldEqual "22.0\n"
}

"Version" in {
val json = Json.fromString("foo")
Printer.spaces2.copy(version = YamlVersion.Yaml1_1).pretty(json) shouldEqual
Expand Down

0 comments on commit 449fe8e

Please sign in to comment.