2

i'm calculating a price using two doubles, however when i output it seem to return it as scientific notation with like 1.785e-05. This is however not intended how do i make sure thats this output it with 8 decimals and not scientific notation?

CODE

let price = tickerObj.price ?? 0
let quantity = Double(self.activeTextField.text ?? "0") ?? 0
let value = quantity / price

topValueField.text = "\(value.rounded(toPlaces: 8))"

ROUND EXTENSION

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
    }
}
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

1 Answers1

0

The number itself is correct as scientific notation. If you want to present a formatted number to the user, it should be a String. Here's working code using a NumberFormatter:

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> String? {
        let fmt = NumberFormatter()
        fmt.numberStyle = .decimal
        fmt.maximumFractionDigits = places
        return fmt.string(from: self as NSNumber)
    }
}

let price = tickerObj.price ?? 0
let quantity = Double(self.activeTextField.text ?? "0") ?? 0
let value = quantity / price

topValueField.text = "\(value.rounded(toPlaces: 8) ?? "Unknown")"
David S.
  • 6,567
  • 1
  • 25
  • 45