ios 在swift中将双精度值四舍五入到x个小数位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27338573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:56:23  来源:igfitidea点击:

Rounding a double value to x number of decimal places in swift

iosswiftdoublenstimeinterval

提问by Leighton

Can anyone tell me how to round a double value to x number of decimal places in Swift?

谁能告诉我如何在 Swift 中将 double 值四舍五入到 x 位小数?

I have:

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With totalWorkTimebeing an NSTimeInterval (double) in second.

totalWorkTime作为一个NSTimeInterval(双)在第二。

totalWorkTimeInHourswill give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

totalWorkTimeInHours会给我小时数,但它给了我这么长的精确数字的时间量,例如 1.543240952039 ......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

打印时如何将其舍入到 1.543 totalWorkTimeInHours

采纳答案by zisoft

You can use Swift's roundfunction to accomplish this.

您可以使用 Swift 的round函数来完成此操作。

To round a Doublewith 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

Double以 3 位精度舍入 a ,首先将其乘以 1000,将其舍入并将舍入后的结果除以 1000:

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236

Other than any kind of printf(...)or String(format: ...)solutions, the result of this operation is still of type Double.

除了任何一种printf(...)String(format: ...)解决方案,此操作的结果仍然是 类型Double

EDIT:
Regarding the comments that it sometimes does not work, please read this:

编辑:
关于它有时不起作用的评论,请阅读:

What Every Programmer Should Know About Floating-Point Arithmetic

每个程序员都应该了解的关于浮点运算的知识

回答by Sebastian

Extension for Swift 2

Swift 2 的扩展

A more general solution is the following extension, which works with Swift 2 & iOS 9:

更通用的解决方案是以下扩展,它适用于 Swift 2 和 iOS 9:

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}



Extension for Swift 3

Swift 3 的扩展

In Swift 3 roundis replaced by rounded:

在 Swift 3 中round被替换为rounded

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}


Example which returns Double rounded to 4 decimal places:


返回四舍五入到小数点后 4 位的 Double 示例:

let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version

回答by vacawama

How do I round this down to, say, 1.543 when I printtotalWorkTimeInHours?

打印时如何将其舍入到 1.543 totalWorkTimeInHours

To round totalWorkTimeInHoursto 3 digits for printing, use the Stringconstructor which takes a formatstring:

要四舍五入totalWorkTimeInHours到 3 位数进行打印,请使用String带有format字符串的构造函数:

print(String(format: "%.3f", totalWorkTimeInHours))

回答by Imanou Petit

With Swift 5, according to your needs, you can choose one of the 9 following stylesin order to have a rounded result from a Double.

使用 Swift 5,您可以根据需要选择以下 9 种样式之一,以便从Double.



#1. Using FloatingPointrounded()method

#1. 使用FloatingPointrounded()方法

In the simplest case, you may use the Doublerounded()method.

在最简单的情况下,您可以使用该Doublerounded()方法。

let roundedValue1 = (0.6844 * 1000).rounded() / 1000
let roundedValue2 = (0.6849 * 1000).rounded() / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#2. Using FloatingPointrounded(_:)method

#2. 使用FloatingPointrounded(_:)方法

let roundedValue1 = (0.6844 * 1000).rounded(.toNearestOrEven) / 1000
let roundedValue2 = (0.6849 * 1000).rounded(.toNearestOrEven) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#3. Using Darwin roundfunction

#3. 使用达尔文round函数

Foundation offers a roundfunction via Darwin.

Foundationround通过 Darwin提供了一个函数。

import Foundation

let roundedValue1 = round(0.6844 * 1000) / 1000
let roundedValue2 = round(0.6849 * 1000) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#4. Using a Doubleextension custom method built with Darwin roundand powfunctions

#4. 使用由DoubleDarwinroundpow函数构建的扩展自定义方法

If you want to repeat the previous operation many times, refactoring your code can be a good idea.

如果您想多次重复之前的操作,重构您的代码可能是一个好主意。

import Foundation

extension Double {
    func roundToDecimal(_ fractionDigits: Int) -> Double {
        let multiplier = pow(10, Double(fractionDigits))
        return Darwin.round(self * multiplier) / multiplier
    }
}

let roundedValue1 = 0.6844.roundToDecimal(3)
let roundedValue2 = 0.6849.roundToDecimal(3)
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#5. Using NSDecimalNumberrounding(accordingToBehavior:)method

#5. 使用NSDecimalNumberrounding(accordingToBehavior:)方法

If needed, NSDecimalNumberoffers a verbose but powerful solution for rounding decimal numbers.

如果需要,NSDecimalNumber提供详细但功能强大的四舍五入十进制数解决方案。

import Foundation

let scale: Int16 = 3

let behavior = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)

let roundedValue1 = NSDecimalNumber(value: 0.6844).rounding(accordingToBehavior: behavior)
let roundedValue2 = NSDecimalNumber(value: 0.6849).rounding(accordingToBehavior: behavior)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#6. Using NSDecimalRound(_:_:_:_:)function

#6. 使用NSDecimalRound(_:_:_:_:)功能

import Foundation

let scale = 3

var value1 = Decimal(0.6844)
var value2 = Decimal(0.6849)

var roundedValue1 = Decimal()
var roundedValue2 = Decimal()

NSDecimalRound(&roundedValue1, &value1, scale, NSDecimalNumber.RoundingMode.plain)
NSDecimalRound(&roundedValue2, &value2, scale, NSDecimalNumber.RoundingMode.plain)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685


#7. Using NSStringinit(format:arguments:)initializer

#7. 使用NSStringinit(format:arguments:)初始化程序

If you want to return a NSStringfrom your rounding operation, using NSStringinitializer is a simple but efficient solution.

如果您想NSString从舍入操作中返回 a ,使用NSString初始化程序是一个简单但有效的解决方案。

import Foundation

let roundedValue1 = NSString(format: "%.3f", 0.6844)
let roundedValue2 = NSString(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685


#8. Using Stringinit(format:_:)initializer

#8. 使用Stringinit(format:_:)初始化程序

Swift's Stringtype is bridged with Foundation's NSStringclass. Therefore, you can use the following code in order to return a Stringfrom your rounding operation:

Swift 的String类型与 Foundation 的NSString类相连。因此,您可以使用以下代码String从舍入操作中返回 a :

import Foundation

let roundedValue1 = String(format: "%.3f", 0.6844)
let roundedValue2 = String(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685


#9. Using NumberFormatter

#9. 使用NumberFormatter

If you expect to get a String?from your rounding operation, NumberFormatteroffers a highly customizable solution.

如果您希望String?从您的舍入操作中获得一个,则NumberFormatter提供高度可定制的解决方案。

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.maximumFractionDigits = 3

let roundedValue1 = formatter.string(from: 0.6844)
let roundedValue2 = formatter.string(from: 0.6849)
print(String(describing: roundedValue1)) // prints Optional("0.684")
print(String(describing: roundedValue2)) // prints Optional("0.685")

回答by Claudio Guirunas

In Swift 2.0 and Xcode 7.2:

在 Swift 2.0 和 Xcode 7.2 中:

let pi: Double = 3.14159265358979
String(format:"%.2f", pi)

Example:

例子:

enter image description here

enter image description here

回答by Krunal Patel

This is a fully worked code

这是一个完整的代码

Swift 3.0/4.0/5.0 , Xcode 9.0 GM/9.2 and above

Swift 3.0/4.0/5.0 , Xcode 9.0 GM/9.2 及以上

let doubleValue : Double = 123.32565254455
self.lblValue.text = String(format:"%.f", doubleValue)
print(self.lblValue.text)

output - 123

输出 - 123

let doubleValue : Double = 123.32565254455
self.lblValue_1.text = String(format:"%.1f", doubleValue)
print(self.lblValue_1.text)

output - 123.3

输出 - 123.3

let doubleValue : Double = 123.32565254455
self.lblValue_2.text = String(format:"%.2f", doubleValue)
print(self.lblValue_2.text)

output - 123.33

输出 - 123.33

let doubleValue : Double = 123.32565254455
self.lblValue_3.text = String(format:"%.3f", doubleValue)
print(self.lblValue_3.text)

output - 123.326

输出 - 123.326

回答by Ash

Building on Yogi's answer, here's a Swift function that does the job:

基于 Yogi 的回答,这里有一个 Swift 函数可以完成这项工作:

func roundToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return round(value * divisor) / divisor
}

回答by jaiswal Rajan

In Swift 3.0 and Xcode 8.0:

在 Swift 3.0 和 Xcode 8.0 中:

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

Use this extension like so:

像这样使用这个扩展:

let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56

回答by Ramazan Karami

The code for specific digits after decimals is:

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

var a = 1.543240952039
var roundedString = String(format: "%.3f", a)

Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:

这里 %.3f 告诉 swift 将这个数字四舍五入到小数点后 3 位。如果你想要双数,你可以使用这个代码:

// String to Double

// 字符串转双

var roundedString = Double(String(format: "%.3f", b))

var roundedString = Double(String(format: "%.3f", b))

回答by Naishta

Swift 4, Xcode 10

斯威夫特 4,Xcode 10

yourLabel.text =  String(format:"%.2f", yourDecimalValue)