我有浮点值1.96,然后我想显示1.9作为字符串,如果我使用String(格式:&#34;%。1f&#34;)结果是2.0,我也尝试使用NumberFormatter作为扩展< / p>
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
formatter.minimumFractionDigits = 1
return formatter.string(for: self)!
但仍然是结果2.0
有没有最好的方法来达到1.96到1.9?
答案 0 :(得分:1)
老把戏:
var yourResult = Double(floor(10*yourDecimalDigit)/10)
// yourResult = 1.9
转换为像这样的字符串
var string = String(yourResult)
答案 1 :(得分:1)
您可以使用Double的常规扩展来截断double值。
Swift 4.0
extension Double {
func truncate(places : Int)-> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
使用如下所示
let trimedValue = 1.96.truncate(places: 1) // 1.9
答案 2 :(得分:0)
也许有方法可以帮助你,但我喜欢自己做
扩展名:
<!doctype html><html lang="en"><head><title>HTTP Status [400] – [Bad Request]</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status [400] – [Bad Request]</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Captcha description not correct</p><p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).</p><hr class="line" /><h3>Apache Tomcat/8.5.15</h3></body></html>
使用它:
extension CGFloat{
var onlyOneDigits : String {
var str = "\(self)"
let count = str.count
if self >= 1000 && self < 10000{
str.removeLast(count - 6)
return str
}else if self >= 100{
str.removeLast(count - 5)
return str
}else if self >= 10{
str.removeLast(count - 4)
return str
}else{
str.removeLast(count - 3)
return str
}
}
}