在Swift中将数字四舍五入至小数点后两位

问题描述:

我正在获取一个数字值,我试图将其转换为两位小数.但是当我将其转换为结果0.00时.这些数字是 0.24612035420731018 .当获得其.2f值时,它显示为0.00.我尝试过的代码是这样,

I'm getting a value of digits which i'm trying to convert to two decimal places. But when i convert it it makes the result to 0.00 . The digits are this 0.24612035420731018 . When get its .2f value it shows 0.00. The code that i tried is this,

 let  digit = FindResturantSerivce.instance.FindResModelInstance[indexPath.row].distance
    let text = String(format: "%.2f", arguments: [digit])
    print(text)

使用格式字符串将其舍入到小数点后两位,并将双精度数转换为字符串:

Use a format string to round up to two decimal places and convert the double to a String:

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

示例:

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

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

如果您想将小数点后一位四舍五入,可以执行以下操作:

If you want to round up your last decimal place, you could do something like this :

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

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