向上舍入到小数点后两位

时间:2016-01-21 17:06:18

标签: swift double

如何将currentRatio四舍五入到小数点后两位?

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

12 个答案:

答案 0 :(得分:98)

使用格式字符串舍入最多两位小数,并将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"

答案 1 :(得分:12)

更新了SWIFT 4以及问题的正确答案

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

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

答案 2 :(得分:10)

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

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

let a = 45.666

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

答案 3 :(得分:7)

考虑使用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

答案 4 :(得分:6)

(Swift 4.2 Xcode 10) 易于使用的扩展程序:-

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

使用:-

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

答案 5 :(得分:4)

小数点后的特定数字代码为:

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

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

答案 6 :(得分:4)

@Rounded,一个快速的5.1属性包装器 例子:

const portfolioItems = document.querySelectorAll('.portfolio-item-wrapper');
    portfolioItems.forEach(portfolioItem => { //pentru fiecare item din portofolioItem vad cand am mouse pe el
        portfolioItem.addEventListener('mouseover', () => {
            portfolioItem.childNodes[1].classList.add('img-darken');//si cand am mouse-ul pe el iau primul copil
            //care este portofolio-img-background
        })
        portfolioItem.addEventListener('mouseout', () => {
            portfolioItem.childNodes[1].classList.remove('img-darken');
        })
    })

答案 7 :(得分:2)

String(format: "%.2f", Double(round(1000*34.578)/1000))

输出:34.58

答案 8 :(得分:2)

为跟我一样的菜鸟提供快速跟进的答案:

通过使用带有输出的功能,您可以使其他答案的实施变得非常容易。例如

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

通过这种方式,只要您想将值保留到小数点后2位,只需键入

两个小数位(“ 您的电话号码”)

...

简单!

P.s。您还可以使它返回 Float 值或任何您想要的值,方法是在String转换后按如下所示再次将其转换:

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

希望有帮助。

答案 9 :(得分:0)

只需一行代码:

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

答案 10 :(得分:0)

如果您给它234.545332233,它将给您234.54

 @Override
  public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
  }

答案 11 :(得分:0)

也许还有:

// 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

保留小数,不截断而是四舍五入

查看更多详情specified rounding rules