ios - 计算双返回科学记数法

标签 ios swift

<分区>

我正在使用两个 double 计算价格,但是当我输出它时,它似乎以科学记数法的形式返回,例如 1.785e-05。然而,这不是故意的,我如何确保这是用 8 位小数而不是科学记数法输出的?

代码

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

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

圆形延伸

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
    }
}

最佳答案

数字本身作为科学记数法是正确的。如果你想向用户呈现一个格式化的数字,它应该是一个字符串。下面是使用 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")"

关于ios - 计算双返回科学记数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876426/

相关文章:

ios - UITableView 静态单元格作为 subview ?

ios - (MVVM) 每个 View 或每个模型的 View 模型?

Swift3 在​​ subview 中的父函数外调用函数

iOS 更改设备扬声器

arrays - 如何在可选中声明 [Int]

ios - 自动布局问题 - 垂直间距

iOS - 高优先级推送 : Insufficient Resources

ios - 当我有多个资源时如何使用 ADAL 库

ios - 自定义 UITableViewCell 中带有 attributedText 的 UILabel : Color not rendering until reuse (iOS10)

ios - dyld : Library not loaded: @rpath/Alamofire. framework/Alamofire 原因:找不到图像