Compare floats to three decimal places

后端 未结 5 2040
不思量自难忘°
不思量自难忘° 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:17

    For float values which can fit into an integer after x1000 you can try:

    if (static_cast(lhs*1000.0) == static_cast(rhs*1000.0))
    {
       // Values are near
    }
    else
    {
       // They are not identical (maybe!)
    }
    

    Be careful of computer accuracy in representing float value.


    IMPORTANT UPDATE

    Always there're numbers which can fail a code, Eric Postpischil's code fails as same as this code.

    Even converting to string doesn't help, we can find numbers which can not convert to strings correctly.

    Well, what is the solution? It's easy, we must define scope and needed accuracy of our program. We can not have unlimited precision in computer world. What Every Computer Scientist Should Know About Floating-Point Arithmetic

提交回复
热议问题