0

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?

Ridho Octanio
  • 543
  • 5
  • 14
Atif Shabeer
  • 167
  • 3
  • 16

1 Answers1

1

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

Vadim Nikolaev
  • 2,132
  • 17
  • 34