I am writing an iOS app in Swift and using Moya as Network layer.
I am making a request object to be send in body and using Moya to perform API call:
struct OrderRequest{
var amount:Double
}
let order=OrderRequest(amount:100.57)
I am converting this object to JSONDict and then to Data.
if let json = JSONDict(from: order) {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
}
I am performing Moya request and internally it's using Alamofire .
ISSUE:
Instead of sending the accurate value of 100.57 , it sends 100.56999999999999
My question is about below line:
let jsonString = String(data: jsonData!, encoding: .utf8)
It converts data from DATA to STRING. This is converting 100.57 to 100.56999999999999
How can it be solved? Am I making the DATA object incorrectly?
That's how binary floating point arithmetic works. About 15 digits precision for Double
, and much less for Float
. What's wrong is not the code, but your expectations. And this is the same in C, C++, Objective-C, Java and so on. Also here you can find the same issue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.