Convert double to float without Infinity

Viewed 95266

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 the further processing I'm doing. I'm okay with loss as long as it is pointing in the general direction as the original number (the relative number 'strength' on all numbers I'm converting must be maintained).

How can I convert float to double and avoid Infinity?

Background:
I'm reading a bytestream from wav/mic, converting it to float, converting it to double, running it through FFT calculation (this is what requires double), and now I want it back to float (storing the data in 32-bit image container).

4 Answers

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.

Related