Skip to content

Commit fec0f16

Browse files
committed
libserialize: Always use a decimal point when emitting a float value
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]
1 parent f102123 commit fec0f16

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/libserialize/json.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,8 @@ fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
386386
fn fmt_number_or_null(v: f64) -> string::String {
387387
match v.classify() {
388388
FPNaN | FPInfinite => string::String::from_str("null"),
389-
_ => f64::to_str_digits(v, 6u)
389+
_ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
390+
_ => f64::to_str_digits(v, 6u) + ".0",
390391
}
391392
}
392393

@@ -2504,8 +2505,8 @@ mod tests {
25042505

25052506
#[test]
25062507
fn test_write_f64() {
2507-
assert_eq!(F64(3.0).to_string().into_string(), "3");
2508-
assert_eq!(F64(3.0).to_pretty_str().into_string(), "3");
2508+
assert_eq!(F64(3.0).to_string().into_string(), "3.0");
2509+
assert_eq!(F64(3.0).to_pretty_str().into_string(), "3.0");
25092510

25102511
assert_eq!(F64(3.1).to_string().into_string(), "3.1");
25112512
assert_eq!(F64(3.1).to_pretty_str().into_string(), "3.1");

0 commit comments

Comments
 (0)