I have a float
-based storage of decimal by their nature numbers. The precision of float
is fine for my needs. Now I want to perform some more precise calculations with these numbers using double
.
An example:
float f = 0.1f;
double d = f; //d = 0.10000000149011612d
// but I want some code that will convert 0.1f to 0.1d;
I know very well that 0.1f != 0.1d. This question is not about precise decimal calculations. In other words...
Let's say I work with an API that returns float
numbers for decimal MSFT stock prices. Believe or not, this API exists:
interface Stock {
float[] getDayPrices();
int[] getDayVolumesInHundreds();
}
It is known that the price of a MSFT share is a decimal number with no more than 5 digits, e.g. 31.455, 50.12, 45.888. Obviously the API does not work with BigDecimal
because it would be a big overhead for the purpose to just pass the price.
Let's also say I want to calculate a weighted average of these prices with double
precision:
float[] prices = msft.getDayPrices();
int[] volumes = msft.getDayVolumesInHundreds();
double priceVolumeSum = 0.0;
long volumeSum = 0;
for (int i = 0; i < prices.length; i++) {
double doublePrice = decimalFloatToDouble(prices[i]);
priceVolumeSum += doublePrice * volumes[i];
volumeSum += volumes[i];
}
System.out.println(priceVolumeSum / volumeSum);
I need a performant implemetation of decimalFloatToDouble
.
Now I use the following code, but I need something more clever:
double decimalFloatToDouble(float f) {
return Double.parseDouble(Float.toString(f));
}