From ec4c896c808e557dc019de52c7148118ccab2fcf Mon Sep 17 00:00:00 2001 From: adamw Date: Thu, 29 Aug 2019 13:28:31 +0200 Subject: [PATCH] #68: properly detect if a number if a float or int --- src/main/scala/io/circe/yaml/Printer.scala | 13 ++++++------- src/test/scala/io/circe/yaml/PrinterTests.scala | 7 ++++++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/scala/io/circe/yaml/Printer.scala b/src/main/scala/io/circe/yaml/Printer.scala index af7dbc0e..05f12c27 100644 --- a/src/main/scala/io/circe/yaml/Printer.scala +++ b/src/main/scala/io/circe/yaml/Printer.scala @@ -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 => @@ -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 } diff --git a/src/test/scala/io/circe/yaml/PrinterTests.scala b/src/test/scala/io/circe/yaml/PrinterTests.scala index ea714fa0..c2810b9a 100644 --- a/src/test/scala/io/circe/yaml/PrinterTests.scala +++ b/src/test/scala/io/circe/yaml/PrinterTests.scala @@ -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.Matchers import org.scalatest.freespec.AnyFreeSpec @@ -103,6 +103,11 @@ class PrinterTests extends AnyFreeSpec 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