Convert double to float without Infinity

后端 未结 4 1880
南笙
南笙 2021-01-17 07:26

I\'m converting double to float using ye old float myFloat = (float)myDouble.

This does however sometimes result in \"Infinity\", which is not good for

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 08:10

    So if the value is greater than float.MaxValue, are you happy for it to just be float.MaxValue? That will effectively "clip" the values. If that's okay, it's reasonably easy:

    float result = (float) input;
    if (float.IsPositiveInfinity(result))
    {
        result = float.MaxValue;
    } else if (float.IsNegativeInfinity(result))
    {
        result = float.MinValue;
    }
    

提交回复
热议问题