Swift 3中的十进制到双精度转换

编程入门 行业动态 更新时间:2024-10-24 18:16:54
本文介绍了Swift 3中的十进制到双精度转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在将项目从 Swift 2.2 迁移到 Swift 3 ,我试图在可能的情况下摆脱旧的Cocoa数据类型。

I'm migrating a project from Swift 2.2 to Swift 3, and I'm trying to get rid of old Cocoa data types when possible.

我的问题在于:将 NSDecimalNumber 迁移到十进制。

My problem is here: migrating NSDecimalNumber to Decimal.

我曾经在 Swift 2.2 :

I used to bridge NSDecimalNumber to Double both ways in Swift 2.2:

let double = 3.14 let decimalNumber = NSDecimalNumber(value: double) let doubleFromDecimal = decimalNumber.doubleValue

现在,切换到 Swift 3 :

let double = 3.14 let decimal = Decimal(double) let doubleFromDecimal = ???

decimal.doubleValue 不存在,也不存在 Double(十进制),甚至十进制为Double ... 我想出的唯一的黑客攻击是:

decimal.doubleValue does not exist, nor Double(decimal), not even decimal as Double... The only hack I come up with is:

let doubleFromDecimal = (decimal as NSDecimalNumber).doubleValue

但是试图摆脱 NSDecimalNumber 是完全愚蠢的,并且必须在虽然...

But that would be completely stupid to try to get rid of NSDecimalNumber, and have to use it once in a while...

嗯,要么我错过了一些显而易见的事情,请原谅浪费你的时间,或者我认为需要解决一个漏洞。 ..

Well, either I missed something obvious, and I beg your pardon for wasting your time, or there's a loophole needed to be addressed, in my opinion...

预先感谢您的帮助。

编辑:没有更多关于 Swift 4 的主题。

Edit : Nothing more on the subject on Swift 4.

推荐答案

在Swift 3中有效的另一个解决方案是投射十进制到 NSNumber 并从中创建 Double 。 / p>

Another solution that works in Swift 3 is to cast the Decimal to NSNumber and create the Double from that.

let someDouble = Double(someDecimal as NSNumber)

更多推荐

Swift 3中的十进制到双精度转换

本文发布于:2023-11-24 19:56:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:精度   Swift   十进制到双

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!