Float rounding (in JSON)

Sergey kornburn at yandex.ru
Thu Oct 13 19:00:30 UTC 2022


I'm not a professional of IEEE 754, but just found this behavior 
at rounding in comparison with other languages. I supose it 
happened because in D float numbers parsed as double and have a 
full length of double while rounding. But this is just doesn't 
match with behavior in other languages.

I'm not sure if this is somehow connected with JSON realizations.

Is it possible in D to have the same results as in others? 
Because explicit formatting is not the answer, since length of 
rounding could be different. That's why just specify "%.XXf" will 
not resolve the issue - two last numbers have 14 and 15 positions 
after the dot.

**Code Python**
```python
import json

str = '{ "f1": 43.476379000000065, "f2": 43.499718999999987, 
"f3": 43.499718000000087, "f4": 43.418052999999986 }'
print(json.loads(str))
```
**Result**
```
{'f1': 43.476379000000065, 'f2': 43.499718999999985, 'f3': 
43.49971800000009, 'f4': 43.418052999999986}
```

**Code Crystal**
```crystal
require "json"

str = "{ \"f1\": 43.476379000000065, \"f2\": 43.499718999999987, 
\"f3\": 43.499718000000087, \"f4\": 43.418052999999986 }"

puts JSON.parse(str)
```
**Result**
```
{"f1" => 43.476379000000065, "f2" => 43.499718999999985, "f3" => 
43.49971800000009, "f4" => 43.418052999999986}
```

**Code D**
```d
import std;

void main() {
     string s = `{ "f1": 43.476379000000065, "f2": 
43.499718999999987, "f3": 43.499718000000087, "f4": 
43.418052999999986 }`;
     JSONValue j = parseJSON(s);
     writeln(j);
}
```
**Result**
```
{"f1":43.4763790000000654,"f2":43.4997189999999847,"f3":43.4997180000000867,"f4":43.4180529999999862}
```


More information about the Digitalmars-d-learn mailing list