Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason that the extra decimal places appear is likely because of a slight precision loss when converting from double to float (floating point conversions are never perfect).</p> <p>If you need to round the number then after you've done the conversion you can do:</p> <pre><code>result = Math.Round(result, 2); </code></pre> <p>Edit: Given Eric's comment below, here is some extra info:</p> <p>A <code>float</code> in C# is a 32 bit floating point representation of a number, whereas a <code>double</code> is 64 bit. Not every number is perfectly representable by a floating point number. When you convert from the 32 bit float to the 64 bit double you've got 32 extra bits to fill in with information. This extra information ends up being the extra digits that you see:</p> <pre><code>float foo = 50.8467178f; double bar = System.Convert.ToDouble(foo); System.Console.WriteLine(bar); // prints 50.8467178344727 on my machine </code></pre> <p>Since the original number is not perfectly representable in floating point, the output ends up being a slightly different number because of the conversion process.</p> <p>If you need to maintain precision for this number you'll need to use <code>decimal</code> values instead:</p> <pre><code>decimal foo = 50.8467178M; double bar = System.Convert.ToDouble(foo); System.Console.WriteLine(bar); // prints 50.8467178 on my machine </code></pre> <p>If you can't use <code>decimal</code> (e.g. the <code>float</code> is the output of a third party library or something) then the rounding approach is the next best option:</p> <pre><code>float foo = 50.8467178f; double bar = System.Convert.ToDouble(foo); bar = System.Math.Round(bar, 7); System.Console.WriteLine(bar); // prints 50.8467178 on my machine </code></pre>
    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.
    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