简体   繁体   中英

decimal 0 precision

I have a scenario in which i have to play with double values. My objective is if somebody enters 37.5 then i have to show the 37.5 and if somebody enter 37.0 then i need to show the 37.0 and if somebody specifically enter 37 then i just need to show 37 not 37.0 Now the problem is i am using double data type for storing these values. double by default converts 37 to 37.0 . and if i truncate the decimal part then one of my scenario fails in which if somebody enters 37.0 then i do need to show the 37.0

Can someone please suggest what should be the best way to achieve the above objective?

A bit hacky, but provides you some idea:

struct DoubleWithPrecision: CustomStringConvertible {

    let value: Double
    private let decimals: Int

    var description: String { return String(format: "%1.\(decimals)f", value) }

    init?(_ string: String) {
        guard let convertedValue = Double(string) else { return nil }

        value = convertedValue

        if let decimalPoint = string.characters.indexOf(".") {
            decimals = string.characters.count - string.startIndex.distanceTo(decimalPoint) - 1
        } else {
            decimals = 0
        }
    }

}

let foo = DoubleWithPrecision("42")!
let bar = DoubleWithPrecision("42.0")!

print(foo) // 42
print(bar) // 42.0

存储用户输入的NSString并仅在需要显示结果时(不截断)应用逻辑

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM