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

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

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`:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
print(string)
}

[1]:

[To see links please register here]

Reply

#12
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:

> // String to Double

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


Reply

#13
//find the distance between two points
let coordinateSource = CLLocation(latitude: 30.7717625, longitude:76.5741449 )
let coordinateDestination = CLLocation(latitude: 29.9810859, longitude: 76.5663599)
let distanceInMeters = coordinateSource.distance(from: coordinateDestination)
let valueInKms = distanceInMeters/1000
let preciseValueUptoThreeDigit = Double(round(1000*valueInKms)/1000)
self.lblTotalDistance.text = "Distance is : \(preciseValueUptoThreeDigit) kms"
Reply

#14
Either:

1. Using `String(format:)`:
- Typecast `Double` to `String` with `%.3f` format specifier and then back to `Double`

Double(String(format: "%.3f", 10.123546789))!

- Or extend `Double` to handle N-Decimal places:

extension Double {
func rounded(toDecimalPlaces n: Int) -> Double {
return Double(String(format: "%.\(n)f", self))!
}
}

2. By calculation
- multiply with 10^3, round it and then divide by 10^3...

(1000 * 10.123546789).rounded()/1000

- Or extend `Double` to handle N-Decimal places:

extension Double {
func rounded(toDecimalPlaces n: Int) -> Double {
let multiplier = pow(10, Double(n))
return (multiplier * self).rounded()/multiplier
}
}
Reply

#15
**Swift 4, Xcode 10**

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

#16
> How do I round this down to, say, 1.543 **when I print** `totalWorkTimeInHours`?

To round `totalWorkTimeInHours` to 3 digits for printing, use the `String` constructor which takes a `format` string:

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

#17
You can add this extension :

extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
}
}

and call it like this :

let ex: Double = 10.123546789
print(ex.clean) // 10.12
Reply

#18
**Use the built in Foundation Darwin library**

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

#19
This seems to work in Swift 5.

Quite surprised there isn't a standard function for this already.

//Truncation of Double to n-decimal places with rounding


~~~Swift
extension Double {

func truncate(to places: Int) -> Double {
return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
}

}
Reply

#20
Here's one for SwiftUI if you need a Text element with the number value.

struct RoundedDigitText : View {
let digits : Int
let number : Double

var body : some View {
Text(String(format: "%.\(digits)f", number))
}
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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