我有一个数字可以说0.00.
0.010.121.2312.34我怎么能用Swift做到这一点?
如何为String扩展添加自定义init方法?
extension String {
init(_ amount: Double, decimalPlaces: UInt) {
self.init()
let decimalFormat = "%0.\(String(decimalPlaces))f"
let currencyAmount = String(format: decimalFormat, amount)
let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign")
let formattedString = "\(currencySign)\(currencyAmount)"
// How to set self to `formattedString` ?
}
}
Run Code Online (Sandbox Code Playgroud)
结果我想看到这样的事情:
let price = Double(155.15)
let formattedPrice = String(price, decimalPlaces: 2) // formattedPrice = "$155.15"
Run Code Online (Sandbox Code Playgroud)
更新:最终解决方案
extension String {
init?(currencyAmount: Double) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: NSLocalizedString("Defaults.LocaleCurrencyFormat", comment: "currency sign")) // Defaults.LocaleCurrencyFormat …Run Code Online (Sandbox Code Playgroud) 我编写了一个简单的 swift 程序来显示运行电气设备的成本。该程序运行良好(只是有点笨拙 - 我是 swift 的新手!)但结果显示小数点后有几个数字,所以我试图将其四舍五入到小数点后两位。我运气不太好!我的代码是:
var pricePerkWh: Double = 13.426
var watts: Double = 5.0
var hours: Double = 730.0
var KW: Double = watts/1000
var kWh: Double = KW*hours
var penceMonth: Double = kWh*pricePerkWh
var poundMonth:Double = penceMonth/100
var cost = poundMonth.roundTo(places: 2)
print ("It will cost £\(cost) per month")
Run Code Online (Sandbox Code Playgroud)
根据我在此处阅读的内容,roundTo(places: 2)已使用,但这导致错误
error: Power Costs.playground:6:12: error: value of type 'Double' has no member 'roundTo'
var cost = poundMonth.roundTo(places: 2)
Run Code Online (Sandbox Code Playgroud)
任何指针将不胜感激!
谢谢
我读了很多书,这NSDecimalNumber是使用货币时最好的格式。
但是,我仍然遇到浮点问题。
例如。
let a: NSDecimalNumber = 0.07 //0.07000000000000003
let b: NSDecimalNumber = 7.dividing(by: 100) //0.06999999999999999
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用Decimal,b就是我期望的:
let b: Decimal = 7 / 100 //0.07
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序中使用核心数据。所以我坚持NSDecimalNumber。除非我想将很多转换NSDecimalNumbers为Decimals。
有人可以帮我得到0.07吗?
似乎是在Swift3中更改了许多语法,我无法找到这个currencyStyle的解决方案我提到的文档没有替换这个.如果有人遇到这个错误,请你点击下面的答案?我在下面提到的链接可以使用
func getCurrencyFormat(amount: Double) -> NSString
{
let amountFormatter = NumberFormatter()
amountFormatter.numberStyle = NumberFormatter.currencyStyle -- ///ERROR
amountFormatter.locale = NSLocale.system
return amountFormatter.string(from: amount as NSNumber)! as NSString
}
Run Code Online (Sandbox Code Playgroud)
引用链接仅适用于swift2 在Swift中使用NSNumberFormatter进行货币争夺