Round double value to 2 decimal places

前端 未结 12 1799
[愿得一人]
[愿得一人] 2020-11-29 18:15

I have a double value as 22.368511 I want to round it to 2 decimal places. i.e. it should return 22.37

How can I do that?

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 18:57

    For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

    var number = 31.726354765
    var intNumber = Int(number * 1000.0)
    var roundedNumber = Double(intNumber) / 1000.0
    

    result: 31.726

提交回复
热议问题