舍入NSDecimalNumber [英] Rounding NSDecimalNumber

查看:138
本文介绍了舍入NSDecimalNumber的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最难找到的东西,似乎应该很简单。我需要准确地将一个NSDecimalNumber舍入到一个特定的小数位数(在运行时确定)。就我所知,我有两个选项,我不喜欢。


  1. 转换为浮动广告并使用C舍入函数:我不喜欢这种情况,因为在这种情况下,精度很重要。浮动广告不一定能准确表示十进制数字,这可能会导致问题。

  2. 使用NSNumberFormatter转换为字符串,然后转换回来:


  3. 有没有另一种方式,我错过了?这是因为它只是似乎丑陋和低效率。有是一个简单的方法来舍入NSDecimalNumbers,但我似乎不知道我的生活是什么。

    解决方案

    您只需用所需的 NSDecimalNumberBehaviors 协议调用 decimalNumberByRoundingAccordingToBehavior: 。请参阅 NSDecimalNumberBehaviors 参考/Reference/Reference.html#//apple_ref/occ/intf/NSDecimalNumberBehaviors\">dev docs



    更新:请参阅 http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/


    I'm having the hardest time figuring out something that seems like it should be very simple. I need to accurately round an NSDecimalNumber to a particular number of decimal places (determined at runtime.) So far as I can tell, I have two options, neither of which I like.

    1. Convert to a float, and use C rounding functions: I don't like this because accuracy matters in this case. Floats can't always accurately represent decimal numbers, and this could cause problems.
    2. Convert to a string using NSNumberFormatter and then convert back: I don't like this one because it just seems ugly and inefficient.

    Is there another way that I've missed? There has got to be an easy way to do rounding of NSDecimalNumbers, but I can't seem to figure out for the life of me what it is.

    解决方案

    You simply call decimalNumberByRoundingAccordingToBehavior:with the desired NSDecimalNumberBehaviors protocol. See the NSDecimalNumberBehaviors reference in the dev docs.

    Update: See http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/

    这篇关于舍入NSDecimalNumber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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