Can anyone tell me how to round a double value to x number of decimal places in Swift?
有谁能告诉我如何用Swift将一个双值四舍五入到小数点后x位?
I have:
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
With totalWorkTime
being an NSTimeInterval (double) in second.
整个工作时间在秒内为NSTimeInterval (double)。
totalWorkTimeInHours
will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......
总工作时间会给出小时数,但它会给出一个很长的精确数字,如1.543240952039
How do I round this down to, say, 1.543 when I print totalWorkTimeInHours
?
当我打印出全部工时时,我如何将其简化为1.543 ?
19 个解决方案
#1
250
You can use Swift's round
function to accomplish this.
您可以使用Swift的圆形函数来实现这一点。
To round a Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:
要圆一个3位精度的双精度圆,先乘以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 Computer Scientist Should Know About Floating-Point Arithmetic
每个计算机科学家都应该了解浮点运算
#2
335
Extension for Swift 2
A more general solution is the following extension, which works with Swift 2 & iOS 9:
更通用的解决方案是使用Swift 2和ios9的扩展:
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
In Swift 3 round
is replaced by rounded
:
在Swift 3轮被圆形取代:
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:
例如,返回四舍五入到小数点后四位的例子:
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
#3
190
Use the String
constructor which takes a format
string:
使用带格式字符串的字符串构造函数:
print(String(format: "%.3f", totalWorkTimeInHours))
#4
102
With Swift 4, according to your needs, you can choose one of the 9 following styles in order to have a rounded result from a Double
.
使用Swift 4,根据您的需要,您可以选择以下9种样式中的一种,以便从Double得到完整的结果。
#1. Using FloatingPoint
rounded()
method
In the simplest case, you may use the Double
round()
method.
在最简单的情况下,可以使用Double round()方法。
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 FloatingPoint
rounded(_:)
method
var roundedValue1 = (0.6844 * 1000).rounded(.toNearestOrEven) / 1000
var roundedValue2 = (0.6849 * 1000).rounded(.toNearestOrEven) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685
#3. Using Darwin round
function
Foundation offers a round
function via 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 Double
extension custom method builded with Darwin round
and pow
functions
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 NSDecimalNumber
rounding(accordingToBehavior:)
method
If needed, NSDecimalNumber
offers 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
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 NSString
init(format:arguments:)
initializer
If you want to return a NSString
from your rounding operation, using NSString
initializer is a simple but efficient solution.
如果希望从舍入操作中返回NSString,使用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 String
init(format:_:)
initializer
Swift’s String
type is bridged with Foundation’s NSString
class (you can learn more about it by reading The Swift Programming Language). Therefore, you can use the following code in order to return a String
from your rounding operation:
Swift的字符串类型与Foundation的NSString类相连接(您可以通过阅读Swift编程语言了解更多)。因此,您可以使用以下代码从您的舍入操作中返回一个字符串:
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
If you expect to get a String?
from your rounding operation, NumberFormatter
offers a highly customizable solution.
如果你期望得到一个字符串?从四舍五入操作中,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")
#5
#6
23
Building on Yogi's answer, here's a Swift function that does the job:
基于Yogi的回答,这里有一个快速的功能:
func roundToPlaces(value:Double, places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
#7
15
This is fully worked code
这是完全工作的代码
Swift 3.0/4.0 , Xcode 9.0 GM/9.2
Swift 3.0/4.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
self.lblValue_1.text = String(format:"%.1f", doubleValue)
print(self.lblValue_1.text)
output - 123.3
输出- 123.3
self.lblValue_2.text = String(format:"%.2f", doubleValue)
print(self.lblValue_2.text)
output - 123.33
输出- 123.33
self.lblValue_3.text = String(format:"%.3f", doubleValue)
print(self.lblValue_3.text)
output - 123.326
输出- 123.326
#8
12
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 this,
使用这个扩展,
let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56
#9
8
A handy way can be the use of extension of type Double
一种方便的方法是使用类型Double的扩展
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
Usage:
用法:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14
#10
7
Use the built in Foundation Darwin library
使用建于达尔文图书馆的基础设施。
SWIFT 3
斯威夫特3
extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return Darwin.round(self * divisor) / divisor
}
}
Usage:
用法:
let number:Double = 12.987654321
print(number.round(to: 3))
Outputs: 12.988
输出:12.988
#11
6
This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.
这是一种长期的变通方法,如果您的需求稍微复杂一点,它可能会派上用场。您可以在Swift中使用numberformatter。
let numberFormatter: NSNumberFormatter = {
let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
Suppose your variable you want to print is
假设您要打印的变量是。
var printVar = 3.567
This will make sure it is returned in the desired format:
这将确保以期望的格式返回:
numberFormatter.StringFromNumber(printVar)
The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.
这里的结果将是“3.6”(四舍五入)。虽然这不是最经济的解决方案,但我之所以给出它,是因为OP提到打印(在这种情况下,字符串不是不需要的),而且因为这个类允许设置多个参数。
#12
6
I would use
我将使用
print(String(format: "%.3f", totalWorkTimeInHours))
and change .3f to any number of decimal numbers you need
把0。3f换成你需要的任何小数
#13
5
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:格式:"% ")3 f”,b))
#14
4
This is more flexible algorithm of rounding to N significant digits
这是一种更灵活的舍入N位有效数字的算法
Swift 3 solution
斯威夫特3解决方案
extension Double {
// Rounds the double to 'places' significant digits
func roundTo(places:Int) -> Double {
guard self != 0.0 else {
return 0
}
let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
return (self * divisor).rounded() / divisor
}
}
// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200
#15
3
Not Swift but I'm sure you get the idea.
不会很快,但我肯定你明白我的意思。
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
#16
3
The best way to format a double property is to use the Apple predefined methods.
格式化双重属性的最好方法是使用Apple预定义的方法。
mutating func round(_ rule: FloatingPointRoundingRule)
FloatingPointRoundingRule is a enum which has following possibilities
浮动点是一个具有以下可能性的枚举
Enumeration Cases:
枚举的案例:
case awayFromZero Round to the closest allowed value whose magnitude is greater than or equal to that of the source.
从零到最接近的允许值,其大小大于或等于源的值。
case down Round to the closest allowed value that is less than or equal to the source.
大小写为最接近的允许值,该值小于或等于源。
case toNearestOrAwayFromZero Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.
从零到最近允许的值;如果两个值相等,则选择较大的值。
case toNearestOrEven Round to the closest allowed value; if two values are equally close, the even one is chosen.
外壳色调均匀,接近最接近的允许值;如果两个值相等,则选择偶数。
case towardZero Round to the closest allowed value whose magnitude is less than or equal to that of the source.
当量值小于或等于源的量值时,则为零。
case up Round to the closest allowed value that is greater than or equal to the source.
以最接近的允许值表示,该值大于或等于源。
var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0
#17
3
round a double value to x number of decimal
NO. of digits after decimal
四舍五入一个双值到小数点后十位数。小数点后的位数
var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y) // 1.5658
var x = 1.5657676754
var y = (x*100).rounded()/100
print(y) // 1.57
var x = 1.5657676754
var y = (x*10).rounded()/10
print(y) // 1.6
#18
0
I found this wondering if it is possible to correct a user's input. That is if they enter three decimals instead of two for a dollar amount. Say 1.111 instead of 1.11 can you fix it by rounding? The answer for many reasons is no! With money anything over i.e. 0.001 would eventually cause problems in a real checkbook.
我发现这个问题想知道是否有可能纠正用户的输入。也就是说,如果他们输入3个小数而不是2个1美元。用1。111代替1。11,你能把它四舍五入吗?答案是否定的!有了钱,任何超过0.001的东西最终都会在真正的支票簿中引起问题。
Here is a function to check the users input for too many values after the period. But which will allow 1., 1.1 and 1.11.
这里有一个函数,用于检查用户在周期结束后输入的太多值。但它允许1。、1.1和1.11。
It is assumed that the value has already been checked for successful conversion from a String to a Double.
假定已经检查了该值,以确定是否成功地从字符串转换为Double。
//func need to be where transactionAmount.text is in scope
func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{
var theTransactionCharac*Three: Character = "A"
var theTransactionCharac*Two: Character = "A"
var theTransactionCharac*One: Character = "A"
var result = false
var periodCharacter:Character = "."
var myCopyString = transactionAmount.text!
if myCopyString.containsString(".") {
if( myCopyString.characters.count >= 3){
theTransactionCharac*Three = myCopyString[myCopyString.endIndex.advancedBy(-3)]
}
if( myCopyString.characters.count >= 2){
theTransactionCharac*Two = myCopyString[myCopyString.endIndex.advancedBy(-2)]
}
if( myCopyString.characters.count > 1){
theTransactionCharac*One = myCopyString[myCopyString.endIndex.advancedBy(-1)]
}
if theTransactionCharac*Three == periodCharacter {
result = true
}
if theTransactionCharac*Two == periodCharacter {
result = true
}
if theTransactionCharac*One == periodCharacter {
result = true
}
}else {
//if there is no period and it is a valid double it is good
result = true
}
return result
}
#19
0
If you want to round Double
values, you might want to use Swift Decimal
so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal
, it can accurately represent decimal values of that rounded floating point value.
如果您想要圆的双值,您可能想要使用Swift小数,这样您就不会引入任何在尝试用这些圆值计算数学时可能出现的错误。如果使用Decimal,它可以精确地表示浮点值的小数。
So you can do:
所以你能做什么:
extension Double {
/// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
///
/// - Parameters:
/// - scale: How many decimal places to round to. Defaults to `0`.
/// - mode: The preferred rounding mode. Defaults to `.plain`.
/// - Returns: The rounded `Decimal` value.
func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
var decimalValue = Decimal(self)
var result = Decimal()
NSDecimalRound(&result, &decimalValue, scale, mode)
return result
}
}
Then, you can get the rounded Decimal
value like so:
然后,可以得到如下所示的十进制整数值:
let foo = 427.3000000002
let value = foo.roundedDecimal(to: 2) // results in 427.30
And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a NumberFormatter
:
如果您想用指定的小数位数显示它(以及为用户当前语言环境定位字符串),您可以使用NumberFormatter:
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
if let string = formatter.string(for: value) {
print(string)
}
#1
250
You can use Swift's round
function to accomplish this.
您可以使用Swift的圆形函数来实现这一点。
To round a Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:
要圆一个3位精度的双精度圆,先乘以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 Computer Scientist Should Know About Floating-Point Arithmetic
每个计算机科学家都应该了解浮点运算
#2
335
Extension for Swift 2
A more general solution is the following extension, which works with Swift 2 & iOS 9:
更通用的解决方案是使用Swift 2和ios9的扩展:
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
In Swift 3 round
is replaced by rounded
:
在Swift 3轮被圆形取代:
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:
例如,返回四舍五入到小数点后四位的例子:
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
#3
190
Use the String
constructor which takes a format
string:
使用带格式字符串的字符串构造函数:
print(String(format: "%.3f", totalWorkTimeInHours))
#4
102
With Swift 4, according to your needs, you can choose one of the 9 following styles in order to have a rounded result from a Double
.
使用Swift 4,根据您的需要,您可以选择以下9种样式中的一种,以便从Double得到完整的结果。
#1. Using FloatingPoint
rounded()
method
In the simplest case, you may use the Double
round()
method.
在最简单的情况下,可以使用Double round()方法。
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 FloatingPoint
rounded(_:)
method
var roundedValue1 = (0.6844 * 1000).rounded(.toNearestOrEven) / 1000
var roundedValue2 = (0.6849 * 1000).rounded(.toNearestOrEven) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685
#3. Using Darwin round
function
Foundation offers a round
function via 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 Double
extension custom method builded with Darwin round
and pow
functions
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 NSDecimalNumber
rounding(accordingToBehavior:)
method
If needed, NSDecimalNumber
offers 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
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 NSString
init(format:arguments:)
initializer
If you want to return a NSString
from your rounding operation, using NSString
initializer is a simple but efficient solution.
如果希望从舍入操作中返回NSString,使用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 String
init(format:_:)
initializer
Swift’s String
type is bridged with Foundation’s NSString
class (you can learn more about it by reading The Swift Programming Language). Therefore, you can use the following code in order to return a String
from your rounding operation:
Swift的字符串类型与Foundation的NSString类相连接(您可以通过阅读Swift编程语言了解更多)。因此,您可以使用以下代码从您的舍入操作中返回一个字符串:
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
If you expect to get a String?
from your rounding operation, NumberFormatter
offers a highly customizable solution.
如果你期望得到一个字符串?从四舍五入操作中,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")
#5
73
In Swift 2.0 and Xcode 7.2:
在Swift 2.0和Xcode 7.2中:
let pi: Double = 3.14159265358979
String(format:"%.2f", pi)
Example:
例子:
#6
23
Building on Yogi's answer, here's a Swift function that does the job:
基于Yogi的回答,这里有一个快速的功能:
func roundToPlaces(value:Double, places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
#7
15
This is fully worked code
这是完全工作的代码
Swift 3.0/4.0 , Xcode 9.0 GM/9.2
Swift 3.0/4.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
self.lblValue_1.text = String(format:"%.1f", doubleValue)
print(self.lblValue_1.text)
output - 123.3
输出- 123.3
self.lblValue_2.text = String(format:"%.2f", doubleValue)
print(self.lblValue_2.text)
output - 123.33
输出- 123.33
self.lblValue_3.text = String(format:"%.3f", doubleValue)
print(self.lblValue_3.text)
output - 123.326
输出- 123.326
#8
12
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 this,
使用这个扩展,
let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56
#9
8
A handy way can be the use of extension of type Double
一种方便的方法是使用类型Double的扩展
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
Usage:
用法:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14
#10
7
Use the built in Foundation Darwin library
使用建于达尔文图书馆的基础设施。
SWIFT 3
斯威夫特3
extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return Darwin.round(self * divisor) / divisor
}
}
Usage:
用法:
let number:Double = 12.987654321
print(number.round(to: 3))
Outputs: 12.988
输出:12.988
#11
6
This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.
这是一种长期的变通方法,如果您的需求稍微复杂一点,它可能会派上用场。您可以在Swift中使用numberformatter。
let numberFormatter: NSNumberFormatter = {
let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
Suppose your variable you want to print is
假设您要打印的变量是。
var printVar = 3.567
This will make sure it is returned in the desired format:
这将确保以期望的格式返回:
numberFormatter.StringFromNumber(printVar)
The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.
这里的结果将是“3.6”(四舍五入)。虽然这不是最经济的解决方案,但我之所以给出它,是因为OP提到打印(在这种情况下,字符串不是不需要的),而且因为这个类允许设置多个参数。
#12
6
I would use
我将使用
print(String(format: "%.3f", totalWorkTimeInHours))
and change .3f to any number of decimal numbers you need
把0。3f换成你需要的任何小数
#13
5
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:格式:"% ")3 f”,b))
#14
4
This is more flexible algorithm of rounding to N significant digits
这是一种更灵活的舍入N位有效数字的算法
Swift 3 solution
斯威夫特3解决方案
extension Double {
// Rounds the double to 'places' significant digits
func roundTo(places:Int) -> Double {
guard self != 0.0 else {
return 0
}
let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
return (self * divisor).rounded() / divisor
}
}
// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200
#15
3
Not Swift but I'm sure you get the idea.
不会很快,但我肯定你明白我的意思。
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
#16
3
The best way to format a double property is to use the Apple predefined methods.
格式化双重属性的最好方法是使用Apple预定义的方法。
mutating func round(_ rule: FloatingPointRoundingRule)
FloatingPointRoundingRule is a enum which has following possibilities
浮动点是一个具有以下可能性的枚举
Enumeration Cases:
枚举的案例:
case awayFromZero Round to the closest allowed value whose magnitude is greater than or equal to that of the source.
从零到最接近的允许值,其大小大于或等于源的值。
case down Round to the closest allowed value that is less than or equal to the source.
大小写为最接近的允许值,该值小于或等于源。
case toNearestOrAwayFromZero Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.
从零到最近允许的值;如果两个值相等,则选择较大的值。
case toNearestOrEven Round to the closest allowed value; if two values are equally close, the even one is chosen.
外壳色调均匀,接近最接近的允许值;如果两个值相等,则选择偶数。
case towardZero Round to the closest allowed value whose magnitude is less than or equal to that of the source.
当量值小于或等于源的量值时,则为零。
case up Round to the closest allowed value that is greater than or equal to the source.
以最接近的允许值表示,该值大于或等于源。
var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0
#17
3
round a double value to x number of decimal
NO. of digits after decimal
四舍五入一个双值到小数点后十位数。小数点后的位数
var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y) // 1.5658
var x = 1.5657676754
var y = (x*100).rounded()/100
print(y) // 1.57
var x = 1.5657676754
var y = (x*10).rounded()/10
print(y) // 1.6
#18
0
I found this wondering if it is possible to correct a user's input. That is if they enter three decimals instead of two for a dollar amount. Say 1.111 instead of 1.11 can you fix it by rounding? The answer for many reasons is no! With money anything over i.e. 0.001 would eventually cause problems in a real checkbook.
我发现这个问题想知道是否有可能纠正用户的输入。也就是说,如果他们输入3个小数而不是2个1美元。用1。111代替1。11,你能把它四舍五入吗?答案是否定的!有了钱,任何超过0.001的东西最终都会在真正的支票簿中引起问题。
Here is a function to check the users input for too many values after the period. But which will allow 1., 1.1 and 1.11.
这里有一个函数,用于检查用户在周期结束后输入的太多值。但它允许1。、1.1和1.11。
It is assumed that the value has already been checked for successful conversion from a String to a Double.
假定已经检查了该值,以确定是否成功地从字符串转换为Double。
//func need to be where transactionAmount.text is in scope
func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{
var theTransactionCharac*Three: Character = "A"
var theTransactionCharac*Two: Character = "A"
var theTransactionCharac*One: Character = "A"
var result = false
var periodCharacter:Character = "."
var myCopyString = transactionAmount.text!
if myCopyString.containsString(".") {
if( myCopyString.characters.count >= 3){
theTransactionCharac*Three = myCopyString[myCopyString.endIndex.advancedBy(-3)]
}
if( myCopyString.characters.count >= 2){
theTransactionCharac*Two = myCopyString[myCopyString.endIndex.advancedBy(-2)]
}
if( myCopyString.characters.count > 1){
theTransactionCharac*One = myCopyString[myCopyString.endIndex.advancedBy(-1)]
}
if theTransactionCharac*Three == periodCharacter {
result = true
}
if theTransactionCharac*Two == periodCharacter {
result = true
}
if theTransactionCharac*One == periodCharacter {
result = true
}
}else {
//if there is no period and it is a valid double it is good
result = true
}
return result
}
#19
0
If you want to round Double
values, you might want to use Swift Decimal
so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal
, it can accurately represent decimal values of that rounded floating point value.
如果您想要圆的双值,您可能想要使用Swift小数,这样您就不会引入任何在尝试用这些圆值计算数学时可能出现的错误。如果使用Decimal,它可以精确地表示浮点值的小数。
So you can do:
所以你能做什么:
extension Double {
/// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
///
/// - Parameters:
/// - scale: How many decimal places to round to. Defaults to `0`.
/// - mode: The preferred rounding mode. Defaults to `.plain`.
/// - Returns: The rounded `Decimal` value.
func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
var decimalValue = Decimal(self)
var result = Decimal()
NSDecimalRound(&result, &decimalValue, scale, mode)
return result
}
}
Then, you can get the rounded Decimal
value like so:
然后,可以得到如下所示的十进制整数值:
let foo = 427.3000000002
let value = foo.roundedDecimal(to: 2) // results in 427.30
And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a NumberFormatter
:
如果您想用指定的小数位数显示它(以及为用户当前语言环境定位字符串),您可以使用NumberFormatter:
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
if let string = formatter.string(for: value) {
print(string)
}