]> git.lizzy.rs Git - rust.git/commitdiff
libserialize: Always use a decimal point when emitting a float value
authorBarosl Lee <vcs@barosl.com>
Sun, 23 Nov 2014 18:14:02 +0000 (03:14 +0900)
committerBarosl Lee <vcs@barosl.com>
Mon, 8 Dec 2014 09:02:53 +0000 (18:02 +0900)
JSON doesn't distinguish between integer and float. They are just
numbers. Also, in the current implementation, a fractional number
without the fractional part is encoded without a decimal point.

Thereforce, when the value is decoded, it is first rendered as Json,
either I64 or U64. This reduces type safety, because while the original
intention was to cast the value to float, it can also be casted to
integer.

As a workaround of this problem, this commit makes the encoder always
emit a decimal point even if it is not necessary. If the fractional part
of a float number is zero, ".0" is padded to the end of the result.

[breaking-change]

src/libserialize/json.rs

index 23e2c4b9830b399e2a3f9645c109ba9d4226d3cd..163fbcdff700cf4a2215c86b9f42a524ecb47f26 100644 (file)
@@ -386,7 +386,8 @@ fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
 fn fmt_number_or_null(v: f64) -> string::String {
     match v.classify() {
         FPNaN | FPInfinite => string::String::from_str("null"),
-        _ => f64::to_str_digits(v, 6u)
+        _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
+        _ => f64::to_str_digits(v, 6u) + ".0",
     }
 }
 
@@ -2504,8 +2505,8 @@ fn test_write_i64() {
 
     #[test]
     fn test_write_f64() {
-        assert_eq!(F64(3.0).to_string().into_string(), "3");
-        assert_eq!(F64(3.0).to_pretty_str().into_string(), "3");
+        assert_eq!(F64(3.0).to_string().into_string(), "3.0");
+        assert_eq!(F64(3.0).to_pretty_str().into_string(), "3.0");
 
         assert_eq!(F64(3.1).to_string().into_string(), "3.1");
         assert_eq!(F64(3.1).to_pretty_str().into_string(), "3.1");