forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreciseFloatSupport.java
More file actions
60 lines (54 loc) · 2.03 KB
/
PreciseFloatSupport.java
File metadata and controls
60 lines (54 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.jsoniter.extra;
import com.jsoniter.spi.JsonException;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jsoniter.spi.Encoder;
import com.jsoniter.spi.JsoniterSpi;
import java.io.IOException;
/**
* default float/double encoding will keep 6 decimal places
* enable precise encoding will use JDK toString to be precise
*/
public class PreciseFloatSupport {
private static boolean enabled;
public static synchronized void enable() {
if (enabled) {
throw new JsonException("PreciseFloatSupport.enable can only be called once");
}
enabled = true;
JsoniterSpi.registerTypeEncoder(Double.class, new Encoder.ReflectionEncoder() {
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
stream.writeRaw(obj.toString());
}
@Override
public Any wrap(Object obj) {
Double number = (Double) obj;
return Any.wrap(number.doubleValue());
}
});
JsoniterSpi.registerTypeEncoder(double.class, new Encoder.DoubleEncoder() {
@Override
public void encodeDouble(double obj, JsonStream stream) throws IOException {
stream.writeRaw(Double.toString(obj));
}
});
JsoniterSpi.registerTypeEncoder(Float.class, new Encoder.ReflectionEncoder() {
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
stream.writeRaw(obj.toString());
}
@Override
public Any wrap(Object obj) {
Float number = (Float) obj;
return Any.wrap(number.floatValue());
}
});
JsoniterSpi.registerTypeEncoder(float.class, new Encoder.FloatEncoder() {
@Override
public void encodeFloat(float obj, JsonStream stream) throws IOException {
stream.writeRaw(Float.toString(obj));
}
});
}
}