How to get a Double value up to 2 Decimal places [duplicate]

那年仲夏 提交于 2020-01-12 11:02:50

问题


In my app I am dealing with currency which is need to upto two decimal digit , I have used number formatter for this to display up to two decimal place but When I want this double value up like 0.7 to 0.70 , I am unable to to do that , type double is always giving me 0.7 but i want 0.7 to 0.70


回答1:


You can simply do this:

let pi = 3.14159

let text = String(format: "%.2f", arguments: [pi])

print(text) // output = 3.14



回答2:


You should use NSNumberFormatter:

let numberFormatter = NSNumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2

let pi = 3.14159
let str = numberFormatter.stringFromNumber(pi)!

print(str)


来源:https://stackoverflow.com/questions/37630269/how-to-get-a-double-value-up-to-2-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!