I know this is an old question, but I believe my answer could help someone.
I really needed float keys.
Of course I ran into the precision problems and my dictionary was much larger than it needed to be (I wanted it to e.g. 1.0
and 0.999998
to be treated as the same). Using fixed-number of decimal digits is not a great solution (e.g. converting it to string as proposed by OP) as it uses absolute error for comparison while relative error is much more universal.
I ended up writing the following method:
float Quantize(float x)
{
const float relMaxQuantError = 0.001f;
float ret = Mathf.Log10(Mathf.Abs(x));
float quantum = Mathf.Log10(1+relMaxQuantError);
ret = Mathf.Floor(ret/quantum) * quantum;
ret = Mathf.Sign(x) * (Mathf.Pow(10, ret));
return ret;
}
I quantize the floats using this method before storing it in the dictionary. The maximum allowed relative error can be controlled by the const (currently it is 0.1 %).
PS: Mathf
is Unity's class. It can be easilly tweaked to use the standard Math
.