舍入到2位小数位 [英] Round up double to 2 decimal places

查看:105
本文介绍了舍入到2位小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 currentRatio 整理为两位小数位?

How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"


推荐答案

字符串可以舍入到两位小数,并将 double 转换为 String

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 = String(format: "%.2f", myDouble) // "3.14"

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

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

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

这篇关于舍入到2位小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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