Moya/Alamofire 请求变量问题

huangapple go评论71阅读模式
英文:

Moya/Alamofire request variables issue

问题

我正在使用Swift编写一个iOS应用程序,并使用**Moya**作为网络层。

我正在创建一个请求对象以在请求主体中发送,并使用Moya执行API调用:

struct OrderRequest {
    var amount: Double
}

let order = OrderRequest(amount: 100.57)

我将此对象转换为JSON字典,然后转换为数据:

if let json = JSONDict(from: order) {
    let data = try JSONSerialization.data(withJSONObject: json, options: [])
}

我正在执行Moya请求,内部使用Alamofire

问题:

而不是发送精确值100.57,它发送100.56999999999999

我的问题是关于下面这行:

let jsonString = String(data: jsonData!, encoding: .utf8)

它将数据从DATA转换为STRING。这将100.57转换为100.56999999999999

如何解决这个问题?我是否错误地创建了数据对象?

英文:

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?

答案1

得分: 1

这就是二进制浮点数算术的工作原理。Double 大约有 15 位的精度,而 Float 的精度要低得多。问题不在于代码,而在于您的期望。在 C、C++、Objective-C、Java 等语言中也是如此。此外,您可以在这里找到相同的问题。

英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 19:38:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定