格式化带未知数字的小数位 [英] Formatting decimal places with unknown number

查看:85
本文介绍了格式化带未知数字的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打印一个我不知道其值的数字.在大多数情况下,该数字为整数或末尾为.5.在某些情况下,该数字以.25或.75结尾,而极少数情况下该数字达到千分之一.我该如何具体检测到最后一种情况?现在,我的代码检测到一个整数(0个小数位),精确地为.5(1个小数位),然后在所有其他情况下恢复为2个小数点,但是当需要时,我需要将其改为3.

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

}

推荐答案

Float使用二进制(IEEE 754)表示形式,不能表示 精确地计算所有小数.例如,

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

let x : Float = 123.456

42f6e979字节存储在x中,这大约等于 123.45600128173828.那么x是否具有3或14个小数位数?

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

如果指定最大数量,则可以使用NSNumberFormatter 应显示的十进制数字:

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


迅速3/4更新:

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

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

这篇关于格式化带未知数字的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆