Skip to content

Commit 87621a0

Browse files
committed
Fix Rust JSON conversions for floats of small magnitude
Fixes #466
1 parent 575a969 commit 87621a0

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

py/jsone/newsfragments/466.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix Rust JSON conversions for floats of small magnitude

rs/src/value.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ fn f64_to_serde_number(value: f64) -> Number {
155155
if value.fract() == 0.0 {
156156
if value < 0.0 && value > -(u32::MAX as f64) {
157157
return (value as i64).into();
158-
} else if value < u32::MAX as f64 {
158+
} else if value >= 0.0 && value < u32::MAX as f64 {
159159
return (value as u64).into();
160160
}
161161
}
@@ -251,9 +251,15 @@ mod test {
251251

252252
#[test]
253253
fn conversions() {
254+
// These floats are chosen such that they exercise the assumption that
255+
// integer values outside (-u32::MAX..u32::MAX) are best represented as
256+
// floats.
257+
let small_float = (-100_000_000_000_000 as i64) as f64;
258+
let big_float = (100_000_000_000_000 as i64) as f64;
259+
254260
let serde_value = json!({
255261
"the": "quick",
256-
"brown": ["fox", 2, 3.5, -5],
262+
"brown": ["fox", 2, 3.5, -5, small_float, big_float],
257263
"over": true,
258264
"the": false,
259265
"lazy": 0,
@@ -270,6 +276,8 @@ mod test {
270276
Number(2.0),
271277
Number(3.5),
272278
Number(-5.0),
279+
Number(small_float),
280+
Number(big_float),
273281
]),
274282
),
275283
("over".to_string(), Bool(true)),

specification.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2274,6 +2274,11 @@ context: {a: 3, b: 2}
22742274
template: {$eval: 'a * b * 3'}
22752275
result: 18
22762276
---
2277+
title: 'multiplication (2)'
2278+
context: {a: 180000000000.0}
2279+
template: {$eval: '(a * -1000)'}
2280+
result: -180000000000000.0
2281+
---
22772282
title: 'division (1)'
22782283
context: {a: 3, b: 2}
22792284
template: {$eval: 'a / b'}

0 commit comments

Comments
 (0)