Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

swift - Formatting decimal places with unknown number

I'm printing out a number whose value I don't know. In most cases the number is whole or has a trailing .5. In some cases the number ends in .25 or .75, and very rarely the number goes to the thousandths place. How do I specifically detect that last case? Right now my code detects a whole number (0 decimal places), exactly .5 (1 decimal), and then reverts to 2 decimal spots in all other scenarios, but I need to go to 3 when it calls for that.

class func getFormattedNumber(number: Float) -> NSString {

    var formattedNumber = NSString()

    // Use the absolute value so it works even if number is negative
    if (abs(number % 2) == 0) || (abs(number % 2) == 1) {  // Whole number, even or odd
        formattedNumber = NSString(format: "%.0f", number)
    }

    else if (abs(number % 2) == 0.5) || (abs(number % 2) == 1.5) {
        formattedNumber = NSString(format: "%.1f", number)
    }

    else {
        formattedNumber = NSString(format: "%.2f", number)
    }

    return formattedNumber

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A Float uses a binary (IEEE 754) representation and cannot represent all decimal fractions precisely. For example,

let x : Float = 123.456

stores in x the bytes 42f6e979, which is approximately 123.45600128173828. So does x have 3 or 14 fractional digits?

You can use NSNumberFormatter if you specify a maximum number of decimal digits that should be presented:

let fmt = NSNumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0

println(fmt.stringFromNumber(123)!)      // 123
println(fmt.stringFromNumber(123.4)!)    // 123.4
println(fmt.stringFromNumber(123.45)!)   // 123.45
println(fmt.stringFromNumber(123.456)!)  // 123.456
println(fmt.stringFromNumber(123.4567)!) // 123.457

Swift 3/4 update:

let fmt = NumberFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0

print(fmt.string(for: 123.456)!) // 123.456

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...