Answer the question
In order to leave comments, you need to log in
Problem with converting decimal to float?
The code:
using System;
public class Program
{
public static void Main()
{
decimal d = 40350m * 63.96m * 0.09m;
Console.WriteLine(d);
string s = "232270.74";
float f1 = Convert.ToSingle(s);
Console.WriteLine(f1.ToString("R"));
float f2 = Convert.ToSingle(s);
Console.WriteLine(f2.ToString("R"));
}
}
Answer the question
In order to leave comments, you need to log in
1) During the conversion of a floating point number to an integer, the fractional part is discarded; no rounding is done. The static class System.Convert provides methods that perform conversions between different numeric types with rounding.
2) An implicit conversion from a large integer type to a floating point type preserves the value, but can sometimes lead to a loss of precision. The reason is that floating point types always have a larger value than integer types, but may have less precision. To demonstrate what has been said, consider an example with a large number:
int i1 = 100000001;
float f = i1; // Value is saved, precision is lost
int i2 = (int)f; // 100000000
3) Rounding errors for real numbers
The float and double types internally represent numbers in binary form. For this reason, only numbers that can be expressed in binary are accurately represented. In practice, this means that most fractional literals (which are decimal) will not be represented exactly.
For example:
float tenth = 0.1f; // Not exactly 0.1
float one = 1f;
Console.WriteLine(one - tenth * 10f); // -1.490116E-08
This is why the float and double types are not suitable for financial calculations. In contrast, the decimal type works in decimal notation and thus can accurately represent numbers expressible in decimal (as well as in base-10 notation such as binary and quinary). Since real literals are decimal, the decimal type can accurately represent numbers such as 0.1. However, neither double nor decimal can accurately represent the fractional part whose decimal representation is periodic:
decimal m = 1M / 6M; // 0.1666666666666666666666666667M
double d = 1.0 / 6.0; // 0.16666666666666666
This results in cumulative rounding errors:
decimal notQuiteWholeM = m+m+m+m+m+m; //
1.0000000000000000000000000002M double notQuiteWholeD = d+d+d+d+d+d; // 0.99999999999999989
which break the equivalence and comparison operations:
Console.WriteLine (notQuiteWholeM == 1M); // Prints False
Console.WriteLine (notQuiteWholeD < 1.0);/ / Prints True
Anders Hejlsberg. The C# Programming Language, 4th Edition
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question