From a1a709495ea64963fddf7d91e1ce4ff0db7d31b8 Mon Sep 17 00:00:00 2001 From: Mike Perham Date: Tue, 24 May 2016 16:07:11 -0700 Subject: [PATCH] Change default float format The current format is lossy in the extreme. This prints the Float as-is with 8 digits of precision. ``` float = Time.now.epoch_f p float.to_json str = String.new(22) do |buffer| LibC.snprintf(buffer, 22, "%.8f", float) len = LibC.strlen(buffer) {len, len} end p str ``` $ crystal tmp.cr "1.46413e+09" "1464131025.34958601" Does the size 22 constant need to be adjusted? --- src/float.cr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/float.cr b/src/float.cr index baa67b0c4f12..b18948996182 100644 --- a/src/float.cr +++ b/src/float.cr @@ -192,7 +192,7 @@ struct Float64 def to_s String.new(22) do |buffer| - LibC.snprintf(buffer, 22, "%g", self) + LibC.snprintf(buffer, 22, "%.8f", self) len = LibC.strlen(buffer) {len, len} end @@ -200,7 +200,7 @@ struct Float64 def to_s(io : IO) chars = StaticArray(UInt8, 22).new(0_u8) - LibC.snprintf(chars, 22, "%g", self) + LibC.snprintf(chars, 22, "%.8f", self) io.write_utf8 chars.to_slice[0, LibC.strlen(chars)] end