我使用哪种Swift数据类型作为货币 [英] Which Swift datatype do I use for currency

查看:224
本文介绍了我使用哪种Swift数据类型作为货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iOS应用程序,它会对代表美元货币的数字执行大量基本算术运算(例如25.00代表25.00美元)。

I have an iOS application that will be performing a lot of basic arithmetic on numbers representing USD currency (eg 25.00 representing $25.00).

我已经进入了很多在Java和Javascript等其他语言中使用数据类型Double的麻烦所以我想知道在Swift中用于货币的最佳数据类型。

I have gotten into a lot of trouble using the datatype Double in other languages like Java and Javascript so I would like to know the best datatype to use for currency in Swift.

推荐答案

使用 NSDecimalNumber 这里有更多信息)。示例:

let a = NSDecimalNumber(integer: 123456)
let b = NSDecimalNumber(integer: 1000)
let c = a.decimalNumberByDividingBy(b)
println(c)
// Result: "123.456"

您可能希望使用这样的扩展名来添加运算符重载到 NSDecimalNumber class。

You will probably want to use an extension like this one to add operator overloading to the NSDecimalNumber class.

这篇关于我使用哪种Swift数据类型作为货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆