在Swift中将数字四舍五入至小数点后两位 [英] Round a digit upto two decimal place in Swift

查看:201
本文介绍了在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"

这篇关于在Swift中将数字四舍五入至小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆