Round up double to 2 decimal places

How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"
167762 次浏览

使用格式字符串四舍五入到小数点后两位,并将 double转换为 String:

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)

例如:

let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"

如果你想四舍五入你的最后一个小数位,你可以这样做(感谢 Phoen1xUK) :

let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"

如果我们想要多次格式化 Double,我们可以使用 Double 的协议扩展,如下所示:

extension Double {
var dollarString:String {
return String(format: "$%.2f", self)
}
}


let a = 45.666


print(a.dollarString) //will print "$45.67"

考虑为此目的使用 NumberFormatter,它提供了更多的灵活性,如果您想打印比率的百分比符号,或者如果您有货币和大数字。

let amount = 10.000001
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let formattedAmount = formatter.string(from: amount as NSNumber)!
print(formattedAmount) // 10
String(format: "%.2f", Double(round(1000*34.578)/1000))

输出: 34.58

小数后特定数字的代码是:

var roundedString = String(format: "%.2f", currentRatio)

这里的% .2 f 告诉 Swift 将这个数字四舍五入到小数点后2位。

更新到 SWIFT 4和问题的正确答案

如果你想四舍五入到小数点后2位,你应该乘以100,然后四舍五入,再除以100

var x = 1.5657676754
var y = (x*100).rounded()/100
print(y)  // 1.57

只有一行代码:

 let obj = self.arrayResult[indexPath.row]
let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])

如果你给它234.545332233它会给你234.54

let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text

(Swift 4.2 Xcode 11) 简单易用扩展:-

extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}

用途:-

if let distanceDb = Double(strDistance) {
cell.lblDistance.text = "\(distanceDb.round(to:2)) km"
}

给像我这样的菜鸟一个简短的回答:

你可以通过使用 带有输出的函数使得其他的答案非常容易实现。

  func twoDecimals(number: Float) -> String{
return String(format: "%.2f", number)
}

这样,每当您想获取一个小数点后两位的值时,只需键入

TwoDecimals (‘ 这是你的号码’)

...

简单!

附言。您也可以让它返回一个 漂浮值,或者任何您想要的值,然后在 String 转换之后再次转换它,如下所示:

 func twoDecimals(number: Float) -> Float{
let stringValue = String(format: "%.2f", number)
return Float(stringValue)!
}

希望能帮上忙。

@ 四舍五入 ,一个迅捷的5.1财产包装 例如:

struct GameResult {
@Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
var score: Decimal
}


var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416

也许还有:

// Specify the decimal place to round to using an enum
public enum RoundingPrecision {
case ones
case tenths
case hundredths
case thousands
}


extension Double {
// Round to the specific decimal place
func customRound(_ rule: FloatingPointRoundingRule, precision: RoundingPrecision = .ones) -> Double {
switch precision {
case .ones: return (self * Double(1)).rounded(rule) / 1
case .tenths: return (self * Double(10)).rounded(rule) / 10
case .hundredths: return (self * Double(100)).rounded(rule) / 100
case .thousands: return (self * Double(1000)).rounded(rule) / 1000
}
}
}


let value: Double = 98.163846
print(value.customRound(.toNearestOrEven, precision: .ones)) //98.0
print(value.customRound(.toNearestOrEven, precision: .tenths)) //98.2
print(value.customRound(.toNearestOrEven, precision: .hundredths)) //98.16
print(value.customRound(.toNearestOrEven, precision: .thousands)) //98.164

保持小数,不截断,但轮流

看到更多的细节甚至 指定的四舍五入规则

试试这个,你会得到一个比0.0更好的结果

extension Double {
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
func toRoundedString(toPlaces places:Int) -> String {
let amount = self.rounded(toPlaces: places)
let str_mount = String(amount)
        

let sub_amountStrings = str_mount.split(separator: ".")
        

if sub_amountStrings.count == 1
{
var re_str = "\(sub_amountStrings[0])."
for _ in 0..<places
{
re_str += "0"
}
return re_str
         

}
else if sub_amountStrings.count > 1, "\(sub_amountStrings[1])".count < places
{
var re_str = "\(sub_amountStrings[0]).\(sub_amountStrings[1])"
let tem_places = (places -  "\(sub_amountStrings[1])".count)
for _ in 0..<tem_places
{
re_str += "0"
}
return re_str
}
        

return str_mount
}
}