Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 486 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rounding a double value to x number of decimal places in swift

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

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With `totalWorkTime` being an NSTimeInterval (double) in second.

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

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

#2
Not Swift but I'm sure you get the idea.

pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
Reply

#3
A handy way can be the use of **extension** of type **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


Reply

#4
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.

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.
Reply

#5
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.

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.

It is assumed that the value has already been checked for successful conversion from a String to a Double.

//func need to be where transactionAmount.text is in scope

func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{


var theTransactionCharacterMinusThree: Character = "A"
var theTransactionCharacterMinusTwo: Character = "A"
var theTransactionCharacterMinusOne: Character = "A"

var result = false

var periodCharacter:Character = "."


var myCopyString = transactionAmount.text!

if myCopyString.containsString(".") {

if( myCopyString.characters.count >= 3){
theTransactionCharacterMinusThree = myCopyString[myCopyString.endIndex.advancedBy(-3)]
}

if( myCopyString.characters.count >= 2){
theTransactionCharacterMinusTwo = myCopyString[myCopyString.endIndex.advancedBy(-2)]
}

if( myCopyString.characters.count > 1){
theTransactionCharacterMinusOne = myCopyString[myCopyString.endIndex.advancedBy(-1)]
}


if theTransactionCharacterMinusThree == periodCharacter {

result = true
}


if theTransactionCharacterMinusTwo == periodCharacter {

result = true
}



if theTransactionCharacterMinusOne == periodCharacter {

result = true
}

}else {

//if there is no period and it is a valid double it is good
result = true

}

return result


}
Reply

#6
I would use

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

and change .3f to any number of decimal numbers you need
Reply

#7
This is more flexible algorithm of rounding to N significant digits

**Swift 3 solution**

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

Reply

#8
The best way to format a double property is to use the Apple predefined methods.

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
Reply

#9
Extension for Swift 2
---------------------

A more general solution is the following extension, which works with 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
}
}

<br/>
Extension for Swift 3
---------------------

In Swift 3 `round` is replaced by `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
}
}

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

#10
**round a double value to x number of decimal** <br>
NO. of digits after decimal<br>

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

Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through