Compare floats to three decimal places

后端 未结 5 2077
不思量自难忘°
不思量自难忘° 2021-01-14 03:44

I wanted to know what would be the fastest approach of comparing floats to three decimal places.Say I have something like this

float lhs = 2.567xxxx
float rh         


        
5条回答
  •  心在旅途
    2021-01-14 04:32

    Convert the float values to strings with the full number of places (std::numeric_limits::dgits10), then truncate the string to 3 decimal places, and compare the resulting strings:

    std::string convert(float value, int places) {
        if (value == 0) {
            return "0";
        }
        int digits(std::numeric_limits::digits10 - std::log(value) / std::log(10));
        digits = std::max(0, digits);
        std::ostringstream out;
        out << std::fixed << std::setprecision(digits) << value;
        std::string rc(out.str());
        return places < digits? rc.substr(0, rc.size() - (digits - places)): rc;
    }
    
    bool compare(float f1, float f2) {
        return convert(f1, 3) == convert(f2, 3);
    }
    

    The various comparisons proposed multiplying by 100 or 1000 don't work because they will do binary rather than decimal rounding. You could try to add 0.5 after multiplying and before truncating to int but there are cases (although few) where this approach still fails. The conversion above, however, does the right thing as long as you don't end up with more than std::numeric_limits::digit10 digits. Trying to deal with more decimal digits than this number will fail because the float can't represent as many decimal digits correctly anyway.

提交回复
热议问题