Convert double to float without Infinity

后端 未结 4 1779
南笙
南笙 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:03

    You can use the .NET method Convert.ToSingle(). For example:

    float newValue = Convert.ToSingle(value);
    

    According to the MSDN Documentation:

    Converts a specified value to a single-precision floating-point number.

    Update: Upon further review, Convert.ToSingle(Double.MaxValue) results in Infinity so you still have to check for infinity as done in Jon Skeet's answer.

提交回复
热议问题