File tree 4 files changed +27
-7
lines changed 4 files changed +27
-7
lines changed Original file line number Diff line number Diff line change @@ -279,6 +279,24 @@ impl Number {
279
279
}
280
280
}
281
281
282
+ pub ( crate ) fn from_f32 ( f : f32 ) -> Option < Number > {
283
+ if f. is_finite ( ) {
284
+ let n = {
285
+ #[ cfg( not( feature = "arbitrary_precision" ) ) ]
286
+ {
287
+ N :: Float ( f as f64 )
288
+ }
289
+ #[ cfg( feature = "arbitrary_precision" ) ]
290
+ {
291
+ ryu:: Buffer :: new ( ) . format_finite ( f) . to_owned ( )
292
+ }
293
+ } ;
294
+ Some ( Number { n } )
295
+ } else {
296
+ None
297
+ }
298
+ }
299
+
282
300
#[ cfg( feature = "arbitrary_precision" ) ]
283
301
/// Not public API. Only tests use this.
284
302
#[ doc( hidden) ]
Original file line number Diff line number Diff line change @@ -40,7 +40,7 @@ impl From<f32> for Value {
40
40
/// let x: Value = f.into();
41
41
/// ```
42
42
fn from ( f : f32 ) -> Self {
43
- From :: from ( f as f64 )
43
+ Number :: from_f32 ( f ) . map_or ( Value :: Null , Value :: Number )
44
44
}
45
45
}
46
46
Original file line number Diff line number Diff line change 1
1
use crate :: error:: { Error , ErrorCode , Result } ;
2
2
use crate :: map:: Map ;
3
- use crate :: number:: Number ;
4
3
use crate :: value:: { to_value, Value } ;
5
4
use alloc:: borrow:: ToOwned ;
6
5
use alloc:: string:: { String , ToString } ;
@@ -149,13 +148,13 @@ impl serde::Serializer for Serializer {
149
148
}
150
149
151
150
#[ inline]
152
- fn serialize_f32 ( self , value : f32 ) -> Result < Value > {
153
- self . serialize_f64 ( value as f64 )
151
+ fn serialize_f32 ( self , float : f32 ) -> Result < Value > {
152
+ Ok ( Value :: from ( float ) )
154
153
}
155
154
156
155
#[ inline]
157
- fn serialize_f64 ( self , value : f64 ) -> Result < Value > {
158
- Ok ( Number :: from_f64 ( value ) . map_or ( Value :: Null , Value :: Number ) )
156
+ fn serialize_f64 ( self , float : f64 ) -> Result < Value > {
157
+ Ok ( Value :: from ( float ) )
159
158
}
160
159
161
160
#[ inline]
Original file line number Diff line number Diff line change @@ -5,5 +5,8 @@ fn test() {
5
5
let float = 5.55f32 ;
6
6
let value = serde_json:: to_value ( & float) . unwrap ( ) ;
7
7
let json = serde_json:: to_string ( & value) . unwrap ( ) ;
8
- assert_eq ! ( json, "5.550000190734863" ) ; // FIXME
8
+
9
+ // If the f32 were cast to f64 by Value before serialization, then this
10
+ // would incorrectly serialize as 5.550000190734863.
11
+ assert_eq ! ( json, "5.55" ) ;
9
12
}
You can’t perform that action at this time.
0 commit comments