【问题标题】:NSPredicate - compare with a rounded intNSPredicate - 与舍入的 int 进行比较
【发布时间】:2017-02-06 20:28:03
【问题描述】:

我目前正在使用以下 NSPredicate 对我拥有的数组进行排序:

        [filteredResults filterUsingPredicate:[NSPredicate predicateWithFormat:@"note.intValue >= %ld", rating]];

基本上,note 元素从 1 变为 5,但它不是 int,而是可以是 4.5、4.75 或 4.2 的浮点数。另一方面,rating 对象是一个 int:它可以是 1、2、3、4 或 5。我想要实现的是,如果 note 是 4.75,则它应该保留在排序中rating 是 5。 换句话说,我想比较 ratingnote,但四舍五入到最接近的一半。

有没有什么方法可以在保持极其简单和有用的 NSPredicate 语法的同时实现这一点?

【问题讨论】:

    标签: sorting nsarray nspredicate


    【解决方案1】:

    检查浮点值是否包含在对应的 间隔:

    [NSPredicate predicateWithFormat:@"note >= %f AND note < %f",
         (double)rating - 0.5, (double)rating + 0.5]
    

    【讨论】:

    • 或者,由于原始谓词只是检查&gt;=,因此只需使用@"note &gt;= %f", (double)rating - 0.25。 (0.25 因为他想要四舍五入到最接近的一半,而不是四舍五入到最接近的 int。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2011-11-24
    • 2020-08-28
    相关资源
    最近更新 更多