快速使用numberformatter解决小数部分的精度问题

    科技2023-11-15  90

    I was creating a calculator app for my class recently when I ran into an issue. Why were some of my calculations coming out all cuckoo bananas?

    遇到问题时,我最近正在为我的课堂创建一个计算器应用程序。 为什么我的一些计算结果全部来自杜鹃香蕉?

    For example, if I put in 2.3 x 3 I would get a result of 6.899999999 instead of 6.9.

    例如,如果我输入2.3 x 3,则结果将是6.899999999,而不是6.9。

    Turns out, this is a universal problem with computer systems where some fractions cannot be stored with exact precision in a binary file system.

    事实证明,这是计算机系统的普遍问题,其中某些分数不能精确地存储在二进制文件系统中。

    Thankfully, in Swift, there is an easy fix using the NumberFormatter class.

    幸运的是,在Swift中,使用NumberFormatter类可以轻松解决问题。

    Here is the code to use. It can be placed in an extension so that it may be used for all Doubles.

    这是要使用的代码。 可以将其放置在扩展名中,以便可用于所有Doubles。

    Then to display the value, you use dot notation to call the function on the variable that holds the value.

    然后,要显示该值,请使用点表示法在保存该值的变量上调用该函数。

    displayLabel.text = newValue.computeDecimal()

    displayLabel.text = newValue.computeDecimal()

    Number formatter also comes in handy when working with currency!

    使用货币时,数字格式化程序也很方便!

    Formatting Currency 格式化货币

    You can even select which currency you would like to format for. By using formatter.locale = .current as above, it will format using the current location of your device. If you would like to set the currency locale, you can do so by setting the Locale identifier. For example, the code below is set for Great Britain.

    您甚至可以选择要格式化的货币。 通过如上所述使用formatter.locale = .current ,它将使用设备的当前位置进行格式化。 如果要设置货币语言环境,可以通过设置语言环境标识符来进行。 例如,以下代码设置为英国。

    formatter.locale = Locale(identifier: “en_GB”)

    formatter.locale =语言环境(标识符:“ en_GB”)

    You can even pull in the currency symbol and set it to a label using:

    您甚至可以使用以下方法拉入货币符号并将其设置为标签:

    currencyLabel.text = formatter.currencySymbol

    currencyLabel.text = formatter.currencySymbol

    This is only the tip of the iceberg of what you can do with NumberFormatter. Check out the Apple Documentation to see what else it can do!

    这只是使用NumberFormatter可以做的冰山一角。 查阅Apple文档 ,看看它还能做什么!

    翻译自: https://medium.com/macoclock/using-numberformatter-in-swift-for-precision-issues-with-fractions-more-bde09922138f

    Processed: 0.016, SQL: 8