You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Examples of well documented but probably unexpected behavior in java / with 32-bit float to 64-bit float conversion.
745
+
assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d );
746
+
assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d );
747
+
Doubled1 = newDouble( 1.1f );
748
+
Doubled2 = newDouble( "1.1f" );
749
+
assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) );
750
+
751
+
assertTrue( "Correctly converting float to double via base10 (string) representation!", newDouble( 3.1d ).equals( newDouble( newFloat( 3.1f ).toString() ) ) );
752
+
753
+
// Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject
754
+
JSONObjectjo = newJSONObject();
755
+
jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double
756
+
assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( newDouble( 3.1d ) ) );
757
+
758
+
JSONObjectinc = newJSONObject();
759
+
inc.put( "bug", newFloat( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value )
760
+
assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceofFloat );
761
+
inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double!
762
+
// this.put(key, (Float) value + 1);
763
+
// 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done.
764
+
// 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects!
765
+
// 3. A float+float operation will be performed and results into a float primitive.
766
+
// 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method
767
+
// put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa
768
+
assertTrue( "JSONObject increment unexpected behavior, Float will not stay Float!", jo.get( "bug" ) instanceofFloat );
769
+
// correct implementation (with change of behavior) would be:
770
+
// this.put(key, new Float((Float) value + 1));
771
+
// Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not
772
+
// really in the the scope of a JSON-library (IMHO.)
0 commit comments