float invalid conversion / float unexpected behavior - c#

I'm trying t wrap my mind around the float behavior (in C#). I have take notice of the floating point precision issue thingy.
I want to convert an floating point string to an float, add + 1 to it and convert it back to a string. The input can be with (never more then 5 decimal places) or without decimals, this is different every time. The output has to be again the full notation (no Scientific notation like: 2.017002E+09F)
It seems to work correctly with the decimal conversion.
Any suggestions for the best practice to get it working with a float?
var inputDecimalStr = "2017002005"; //2017002005.55 has the same result for the float conversion
float floatRegNr = 0;
float.TryParse(inputDecimalStr, out floatRegNr); // somehow this converts to 2.017002E+09
decimal test1 = decimal.Parse(inputDecimalStr); // this seems to work
float test2 = Convert.ToSingle(test1); // somehow this converts to 2.017002E+09
float test3 = Single.Parse(inputDecimalStr, NumberStyles.Float, CultureInfo.InvariantCulture);
float test4 = 2017002005F;
float test5 = 2.017002E+09F;
float test6 = 2.017002005E+09F;
double test7 = 234423.33D;
//this works ok
test5.ToString("0." + new string('#', 339));
test1.ToString();

If you use this tool that shows you the binary representation of float, you get that 2017002005 is represented as 0x4ef07204, which translated back to decimal form becomes 2017001984 (an error of 21 out of the conversion).
If you change the least significative bit of the number (i.e. the minimum change that can be registered) you get 0x4ef07205, which represents 2017002112 (107 more than 2017002005 + 1.
If this level of detail is important, you can use fixed point arithmetic. Since you only want to add 1, split the number into integer and decimal parts, add 1 to the integer part and then convert back to String each part separately.

Related

C#. Strange behavior of double

Here is the code which made me post this question.
// int integer;
// int fraction;
// double arg = 110.1;
this.integer = (int)(arg);
this.fraction = (int)((arg - this.integer) * 100);
The variable integer is getting 110. That's OK.
The variable fraction is getting 9, however I am expecting 10.
What is wrong?
Update
It seems I have discovered that the source of the problem is subtraction
arg - this.integer
Its result is 0.099999999999994316.
Now I am wondering how I should correctly subtract so that the result was 0.1.
You have this:
fraction = (int)((110.1 - 110) * 100);
The inner part ((110.1 - 110) * 100), will be 9.999999
When you cast it to int, it will be round off to 9
This is because of "floating point" (see here) limitations:
Computers always need some way of representing data, and ultimately
those representations will always boil down to binary (0s and 1s).
Integers are easy to represent, but non-integers are a bit more
tricky. Consider the following var:
double x = 0.1d;
The variable x will actually store the closest available double to
that value. When you understand this, it becomes obvious why some
calculations seem to be "wrong".
If you were asked to add a third to a third, but could only use 3
decimal places, you'd get the "wrong" answer: the closest you could
get to a third is 0.333, and adding two of those together gives 0.666,
rather than 0.667 (which is closer to the exact value of two thirds).
Update:
In financial applications or where the numbers are so important to be exact, you can use decimal data type:
(int)((110.1m - 110) * 100) //will be 10 (m is decimal symbol)
or:
decimal arg = 110.1m;
int integer = (int)(arg); //110
decimal fraction = (int)((arg - integer) * 100); //will be 10
It is because you are using double, precision gets rounded, if you want it to be 10 use decimal type:
check the following:
int integer;
int fraction;
decimal arg = 110.1M;
integer = (int)(arg);
decimal diff = arg - integer;
decimal multiply = diff * 100;
fraction = (int)multiply;//output will be 10 as you expect

Rounding to 2 decimal places c#

Currently have a working rounding model within my c# code and is perfectly rounding numbers that have more than 2 decimal places down to 2 decimal places which is great. However, when i have lets say double value = 100.6, and i put that into double dollar_value = Math.Round(value, 2), it still returns as 100.6.
I was wondering if there was a way to transform a 1 decimal place value to 2 decimal places?
Numbers are not stored with extra zeroes (As it is a waste of memory to do so, being the numbers are the same with or without). In order to represent a number this way you will either need to display or store it as a string.
string str = value.ToString("#.00", CultureInfo.InvariantCulture);
Now str will always have 2 decimal places.
I don't know the C# method, but in C++ I'd use one of these two methods:
double value = 23.666666 ; // example
value = 0.01 * floor ( value * 100.0 ) ; // There's a "floor" function in C# too
^ See https://msdn.microsoft.com/en-us/library/e0b5f0xb(v=vs.110).aspx
Or
double value = 23.666666 ; // example
value = 0.01 * (double) ( (int)(value*100.0) ) ;
Or
double value = 23.666666 ; // example
value = 0.01 * double ( int ( value*100.0 ) ) ; // same as previous, but more C++ like
The other answers are probably better if you're looking to "print a dollar amount with two decimal places." However, if you want to transform the number to use internally, this is a way to do it.
If you want the string representation to have two decimal points use:
yourNumber.ToString ("0.00");
The number itself is always stored as a ~29 digit number regardless of its string representation.
Your value just needs to be formatted when it's display - for example value.ToString("N2") will convert it to a string with two decimal places. Check out the Standard Numeric Format Strings on MSDN to see a broader list of formatting strings.
Additionally, I'd only convert to a string when you're ready display the value to a user and would keep it as a numeric type (e.g. double) if you're passing it around between methods or planning to do any further calculations on it. Otherwise you'll be unnecessarily converting the value to and from a string multiple times.

Float to String Conversion

I want to convert float value to string.
Below is the code which i am using for the conversion.
static void Main(string[] args)
{
string s =string.Format("{0:G}", value);
Console.Write(s);
Console.ReadLine();
}
and it outputs as 2.5
But my problem is i want to get the value as 2.50 because i want to compare it with original value later in my project.
so please suggest me if there are any ways to do it?
You should be using {0:N2} to format to two decimal places.
string.Format("{0:N2}", 2.50)
For 3 decimal places:
string.Format("{0:N3}", 2.50)
And so on.
You can also store the value in a string this way without worrying about precision and then convert your value where you are testing for comparison as string:
string strDecimalVal = Convert.ToString( 2.5000001);
because i want to compare it with original value later in my project.
...then you will need to store the number of decimal places the original value had. Once the value is a float, this information is lost. The float representations of 2.5, 2.50 and 2.500 are exactly the same.
So, basically, you have the following possibilities (in order of preference):
Don't do a string comparison between the old and the new value. Convert both values to float and then compare them (with a margin of error since floats are not precise).
Store the number of decimal places of the old value and then use myFloat.ToString("F" + numDecimals.ToString()) to convert it to a string.
Store the value as a string instead of a float. Obviously, you won't be able to do math on that value.
Alternatively, if you do not insist on using floats, decimals might suit your purpose: The do store the number of significant digits:
decimal x = Decimal.Parse("2.50", CultureInfo.InvariantCulture);
decimal y = Decimal.Parse("2.500", CultureInfo.InvariantCulture);
Console.WriteLine(x.ToString()); // prints 2.50
Console.WriteLine(y.ToString()); // prints 2.500
Try this
Console.WriteLine("{0:F2}", 2.50);
Console.WriteLine("{0:0.00}", 2.50);
Console.WriteLine("{0:N2}", 2.50);
Version 1 and 2 are almost similar, but 3 is different. 3 will include number separators when number is large.
For example the following outputs 454,542.50
Console.WriteLine("{0:N2}", 454542.50);
More on MSDN

Float wrong calculation [duplicate]

This question already has answers here:
Why am I getting the wrong result when using float? [duplicate]
(4 answers)
Float is converting my values
(4 answers)
Closed 9 years ago.
The result must be 806603.77 but why I get 806603.8 ?
float a = 855000.00f;
float b = 48396.23f;
float res = a - b;
Console.WriteLine(res);
Console.ReadKey();
You should use decimal instead because float has 32-bit with 7 digit precision only that is why the result differs, on other hand decimal has 128-bit with 28-29 digit precision.
decimal a = 855000.00M;
decimal b = 48396.23M;
decimal res = a - b;
Console.WriteLine(res);
Console.ReadKey();
Output: 806603.77
A float (also called System.Single) has a precision equivalent to approximately seven decimal figures. Your res difference needs eight significant decimal digits. Therefore it is to be expected that there is not enough precision in a float.
ADDITION:
Some extra information: Near 806,000 (806 thousand), a float only has four bits left for the fractional part. So for res it will have to choose between
806603 + 12/16 == 806603.75000000, and
806603 + 13/16 == 806603.81250000
It chooses the first one since it's closest to the ideal result. But both of these values are output as "806603.8" when calling ToString() (which Console.WriteLine(float) does call). A maximum of 7 significant decimal figures are shown with the general ToString call. To reveal that two floating-point numbers are distinct even though they print the same with the standard formatting, use the format string "R", for example
Console.WriteLine(res.ToString("R"));
Because float has limited precision (32 bits). Use double or decimal if you want more precision.
Please be aware that just blindly using Decimal isn't good enough.
Read the link posted by Oded: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Only then decide on the appropriate numeric type to use.
Don't fall into the trap of thinking that just using Decimal will give you exact results; it won't always.
Consider the following code:
Decimal d1 = 1;
Decimal d2 = 101;
Decimal d3 = d1/d2;
Decimal d4 = d3*d2; // d4 = (d1/d2) * d2 = d1
if (d4 == d1)
{
Console.WriteLine("Yay!");
}
else
{
Console.WriteLine("Urk!");
}
If Decimal calculations were exact, that code should print "Yay!" because d1 should be the same as d4, right?
Well, it doesn't.
Also be aware that Decimal calculations are thousands of times slower than double calculations. They are not always suitable for non-currency calculations (e.g. calculating pixel offsets or physical things such as velocities, or anything involving transcendental numbers and so on).

Float is converting my values

I have a method that tests a value is within the range allowed on fields. If it is outside the range returns null and if inside returns the value.
internal float? ExtractMoneyInRangeAndPrecision(string fieldValue, string fieldName, float min, float max, int scale, int lineNumber)
{
float returnValue;
//Check whether valid float if
if (float.TryParse(fieldValue, out returnValue))
{
//Check whether in range
if (returnValue >= min && returnValue <= max)
{
int decPosition = 0;
decPosition = fieldValue.IndexOf('.');
if (
(decPosition == -1) ||
((decPosition != -1) && (fieldValue.Substring(decPosition, fieldValue.Length - decPosition).Length -1 <= scale))
)
{
return returnValue;
}
}
}
return null;
}
Here is my unit test:
[TestMethod()]
[DeploymentItem("ImporterEngine.dll")]
public void ExtractMoneyInRangeAndPrecisionTest_OutsideRange()
{
MockSyntaxValidator target = new MockSyntaxValidator("", 0);
string fieldValue = "1000000";
string fieldName = "";
float min = 1;
float max = 999999.99f;
int scale = 2;
int lineNumber = 0;
float? Int16RangeReturned;
Int16RangeReturned = target.ExtractMoneyInRangeAndPrecision(fieldValue, fieldName, min, max, scale, lineNumber);
Assert.IsNull(Int16RangeReturned);
}
As you can see the max is 999999.99 but when the method takes it in it changes it to 1,000,000
Why is this?
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
In short, because of the way floating-point numbers represent real numbers, the number you assign to a float is not always the number you get back out. The value you specify is converted to the nearest value that can be represented in scientific notation with a magnitude determined by a base of 2.
In the case of 999999.99, the nearest number that can be represented as a float with the same number of sig figs is 7.6293945 * 217 = 999999.99504, which when rounded to the same sig figs is 1,000,000.00. This may not be the EXACT case, but error like this is inherent in the use of floats.
Do not use floating-point types in situations where the accuracy of the number at a given level of precision is required. Instead, use the decimal type, which will retain the precision of values entered.
Not every string of digits can be converted to a float. Without checking, I would say that 999999.99 is one such number. A decimal would solve this.
The float type doesn't have enough precision to do what you want to do. I would recommend using the decimal type. Floats can be accurate to 7 decimal digits at most, and you're using 8 here. Decimal can have up to 28 digits, which is more than enough for any amount. Moreover, unlike float, the value the compiler uses and the value you write will always be the same.
Here's the long explanation:
Floats (single-precision floating-point numbers) are stored as an integer times a power of two, where the integer is in a certain range (between 2^23 and 2^24).
When you write a decimal number in your code, the compiler interprets this as the number in this form that is closest to the number you wrote. Sometimes the match is exact (99999.75). In other cases, your number needs to be rounded to the closest floating-point number. This is what happened here:
99999.99 = 2^19 * 1.907348613739013671875
= 2^19 * 2^-23 * (2^23 * 1.907348613739013671875)
= 2^-4 * 15999999.84
The closest integer to 15999999.84 is 16000000, so the rounded value is
(float)99999.99 = 2^-4 * 16000000
= 1000000
The big advantage of the decimal type is that is represented as a 96 bit integer times a power of 10, so decimal numbers with up to 28 digits can be represented exactly, without any rounding. What you see is what you get.
The biggest disadvantage of decimal is that it is significantly slower, but in a situation like this where you're converting strings to numbers, this is not a factor.
Floating-point types (as defined in C#) are approximate. For precision you should always use decimal.
From MSDN:
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.
http://msdn.microsoft.com/en-us/library/364x0z75.aspx
There seems to be some dispute about what qualifies as a floating-point type in C#. While decimal does qualify as a floating-point type by actual definition, it is not defined as such according to the MSDN specification.
http://msdn.microsoft.com/en-us/library/9ahet949.aspx

Categories

Resources