How dangerous is it to compare floating point values?

前端 未结 11 1010
囚心锁ツ
囚心锁ツ 2020-11-21 06:44

I know UIKit uses CGFloat because of the resolution independent coordinate system.

But every time I want to check if for example fram

11条回答
  •  没有蜡笔的小新
    2020-11-21 07:07

    I am using the following comparison function to compare a number of decimal places:

    bool compare(const double value1, const double value2, const int precision)
    {
        int64_t magnitude = static_cast(std::pow(10, precision));
        int64_t intValue1 = static_cast(value1 * magnitude);
        int64_t intValue2 = static_cast(value2 * magnitude);
        return intValue1 == intValue2;
    }
    
    // Compare 9 decimal places:
    if (compare(theView.frame.origin.x, 0, 9)) {
        // do important operation
    }
    

提交回复
热议问题