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).
Using TypeCasting to Convert Double to Float in JavaTo define a float type, we must use the suffix f or F , whereas it is optional to use the suffix d or D for double. The default value of float is 0.0f , while the default value of double is 0.0d . By default, float numbers are treated as double in Java.
The floatValue() method returns the double value converted to type float .
In C# I can convert doubles to floats by a cast (float) or by Convert. ToSingle() . double x = 3.141592653589793238463; float a = (float)x; float b = Convert.
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;
}
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.
If a calculation result of a calculation exceeds the range of the type you're storing it in, it will be necessary to do one of three things:
There are many applications where the third approach would be the right one. In such situations, however, if it would make sense to peg the reading at a value of a million, then it shouldn't matter whether the computation results in a value of 1,000,001 or 1E+39 (floating-point +INF). One should peg to a million in either case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With