Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen is it beneficial to convert from float to double via decimal
    primarykey
    data
    text
    <p>Our existing application reads some floating point numbers from a file. The numbers are written there by some other application (let's call it <em>Application B</em>). The format of this file was fixed long time ago (and we cannot change it). In this file all the floating point numbers are saved as floats in binary representation (4 bytes in the file). </p> <p>In our program as soon as we read the data we convert the floats to doubles and use doubles for all calculations because the calculations are quite extensive and we are concerned with the spread of rounding errors.</p> <p>We noticed that when we convert floats via decimal (see the code below) we are getting more precise results than when we convert directly. Note: Application B also uses doubles internally and only writes them into the file as floats. Let's say Application B had the number 0.012 written to file as float. If we convert it after reading to decimal and then to double we get exactly 0.012, if we convert it directly, we get 0.0120000001043081. </p> <p>This can be reproduced without reading from a file - with just an assignment: </p> <pre><code> float readFromFile = 0.012f; Console.WriteLine("Read from file: " + readFromFile); //prints 0.012 double forUse = readFromFile; Console.WriteLine("Converted to double directly: " + forUse); //prints 0.0120000001043081 double forUse1 = (double)Convert.ToDecimal(readFromFile); Console.WriteLine("Converted to double via decimal: " + forUse1); //prints 0.012 </code></pre> <p>Is it always beneficial to convert from float to double via decimal, and if not, under what conditions is it beneficial?</p> <p>EDIT: Application B can obtain the values which it saves in two ways:</p> <ol> <li>Value can be a result of calculations</li> <li>Value can be typed in by user as a decimal fraction (so in the example above the user had typed 0.012 into an edit box and it got converted to double, then saved to float)</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload