双精度舍入到小数点后两位

问题描述 投票:0回答:14

如何将

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

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"
swift double
14个回答
260
投票

使用格式字符串四舍五入到小数点后两位并将

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"

72
投票

(斯威夫特 4.2 Xcode 11) 易于使用扩展:-

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

用途:-

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

40
投票

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

如果您想四舍五入到小数点后两位,您应该乘以 100,然后四舍五入,然后除以 100

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

18
投票

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

17
投票

对于像我这样的菜鸟来说只是一个快速的后续答案:

您可以通过使用带有输出的函数使其他答案变得非常容易实现。例如

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

这样,每当您想要获取小数点后两位的值时,只需键入

twoDecimals('这里是您的数字')

...

简单!

P.s.您还可以使其返回 Float 值或任何您想要的值,然后在字符串转换后再次转换它,如下所示:

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

希望有帮助。


15
投票

添加到上面的答案中,如果我们想多次格式化 Double,我们可以使用 Double 的协议扩展,如下所示:

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

let a = 45.666

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

6
投票

小数点后具体数字的代码是:

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

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


5
投票

@Rounded,一个 swift 5.1 属性包装器 示例:

struct GameResult {
    @Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
    var score: Decimal
}

var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416

3
投票

也许还有:

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

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

查看更多详细信息,甚至指定的舍入规则


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

输出:34.58


1
投票

试试这个,你会得到更好的结果而不是0.0

extension Double {
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
    func toRoundedString(toPlaces places:Int) -> String {
        let amount = self.rounded(toPlaces: places)
        let str_mount = String(amount)
        
        let sub_amountStrings = str_mount.split(separator: ".")
        
        if sub_amountStrings.count == 1
        {
          var re_str = "\(sub_amountStrings[0])."
            for _ in 0..<places
            {
                re_str += "0"
            }
            return re_str
         
        }
        else if sub_amountStrings.count > 1, "\(sub_amountStrings[1])".count < places
        {
            var re_str = "\(sub_amountStrings[0]).\(sub_amountStrings[1])"
            let tem_places = (places -  "\(sub_amountStrings[1])".count)
              for _ in 0..<tem_places
              {
                  re_str += "0"
              }
            return re_str
        }
        
        return str_mount
    }
}

0
投票

TL;博士

extension Double {
    /// Returns the value rounded to the specified precision places and rounding rule with a small epsilon to correct imprecision of floating point arithmetic. The schoolbook rounding rule is used by default.
    /// > Tip: You can also use .toNearestOrEven (bankers rounding) to avoid positive bias (which may be important in statistics or analytics). Or you can use .towardZero if you want to truncate instead of rounding the rest.
    func approximated(to places: Int = 2, rule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Double {
        let multiplier = pow(10.0, Double(places))
        let epsilon = multiplier.ulp // Adding a small epsilon value based on the unit in the last place (ULP) of the multiplier is a way to handle the imprecision of floating-point arithmetic. This approach ensures that the rounding behaves as expected, even for edge cases.
        let shifted = self < 0 ? (self * multiplier) - epsilon : (self * multiplier) + epsilon
        let rounded = shifted.rounded(rule)
        let normalized = rounded / multiplier
        
        return normalized
    }
}

print("# test extension")   
let nums = [ 1.005, 1.0049, -1.005, -1.0045]
// expected: 1.01   1.00    -1.01   -1.00

nums.forEach { print($0.approximated(), terminator: " ") }
// 1.01 1.0 -1.01 -1.0

print("\n# String(format:)")
nums.forEach { print(String(format: "%.2f", $0), terminator: " ") }
// 1.00 1.00 -1.00 -1.00 

import Foundation

说明

您有多种方法来舍入浮点值,但无论您选择哪种方法,您都应该意识到您正在使用不精确的值,因此结果可能不是您所期望的。

如果您想像人类期望的那样看到舍入,您可以使用上面的

approximated
函数。

如果您想将浮点值格式化为任何其他编程语言都会解释的格式,请使用:

String(format: "%.2f", myDouble)
表示小数点后的两个值。但预计 0.005 会变成 0.00,而不是 0.01

另请记住,当您使用简单的

print(myDouble)
时,它也会默认四舍五入,因此它不是存储的实际数字。要查看确切的数字,您可以使用:

let myDouble = 1.005
print(String(format: "%.60g", myDouble))
// 1.00499999999999989341858963598497211933135986328125

g
而不是
f
意味着如果数字使用的数字少于 60 位,您不希望在右侧看到多余的零(虽然从技术上讲您可以要求更多,但 Double 的精度将有意义的数字限制为大约15-17。除此之外,附加数字将为零或可能不准确)。 这些额外的数字是二进制到十进制的限制和转换过程的结果。因此,您还可以使用
String(format: "%.17f", myDouble)
以有意义的精度查看您的数字。


-2
投票

如果你给它 234.545332233 它会给你 234.54

let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text

-6
投票

只需一行代码:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])
© www.soinside.com 2019 - 2024. All rights reserved.