String to float C#, odd result [duplicate] - c#

This question already has answers here:
C# String to Float Conversion
(5 answers)
Closed 7 years ago.
In my code I want to convert a string to a float. But when I conver something like 49.5 to a float, it gives the output 495 instead of 49.5 how can I solve this?
float.Parse, Single.Parse or Convert.ToSingle(); give all the same result...
String[] splittedLine = new String[25];
splittedLine = foundLine.Split('-');
float Z = float.Parse(splittedLine[2]);
float X = float.Parse(splittedLine[3]);
float Y = Single.Parse(splittedLine[4]);
PointF Center = new PointF(X /2, Y /2);
the values in the X & Y are or a full number (example 207 or 49.5);
foundLine is a line from a textdocument.
So how can I that the value from the text file (49.5) will stay 49.5 instead of 495?

Probably your system has a different format for fractional numbers than what your file was written with.
By default, float.Parse will use your system's locale settings to decide on this. To manually specify a format, you can use another overload:
float.Parse(splittedLine[2], CultureInfo.InvariantCulture);

Related

Multiplying a float rounds numbers inconsistently. How to multiply without rounding? [duplicate]

This question already has answers here:
C# Maths gives wrong results!
(4 answers)
Closed 9 months ago.
Hi I have the function:
public static string MapDiePitchY(string DiePitchY)
{
float value = float.Parse(DiePitchY) * 1000;
int valInt = (int)value;
string temp = valInt.ToString();
return temp;
}
When I run it with these two numbers, I get two different behaviours:
str = MapDiePitchY("4150.8");
Returns 4150799
While
str = MapDiePitchY("2767.3");
Returns
2767300 which is what I'd expect and want everytime I pass in a float
I want the function to always return the value multiplied by 1000 but with no rounding. I've tried to replace the 1000 with 1000f and still get the behaviour where it adds extra value to 4150.8. Values that shouldn't exist there. I have no idea why this is happenign and googling hasn't given me any answers.
Is there a way to ensure I get the exact value I pass in as string but multiplied by 1000 with no rounding?
I am on C# 7.3
So you understand floating-point numbers are not exact. When you type float x = 4150.8f the internal bit representation of the number is
x = (1 + 112230 * 2^(-23)) * 2^(139-127) = 4150.7998046875
The integers m=112230 and e=139 represent the mantissa and exponent of the floating-point number.
The above is the result of the parse function. Then you multiply by 1000 which results in
value = x*1000 = 4150799.8046875
what you want to do at this point is do the rounding before converting into an integer
int valInt = (int)Math.Round(value);
which should round up the .80.. in the end into the next whole number 4150800.

How to convert integer 999999999 to float 999999999.0 instead of 1000000000.0 in C#? [duplicate]

This question already has an answer here:
Why does my float of 999999999 become 10000000000? [duplicate]
(1 answer)
Closed 4 years ago.
In C#, to convert int to float, we just need to do something like float floatNumber = intNumber or Convert.ToSingle(intNumber). However, when it comes to large number such as 999999999, the system cannot correctly convert the number but convert it into the unwanted number 1E+09. Now the question is, is it possible to convert that large integer into the wanted float number?
A 32-bit float can't exactly represent an integer that large: It only has 24 bits with which to do it (one is implicit in the format). In 24 bits you can represent 16777215. 16777216 also fits because it is a power of two. 999999999 can't be represented exactly as a number with at most 24 bits multiplied by a power of 2.
See this answer on SO: https://stackoverflow.com/a/3793950/751579
For more information look up details on IEEE floating point 32-bit and 64-bit formats.
Can you use decimal type?
Console.WriteLine(999999999.0f.ToString("N"));
Console.WriteLine(999999999.0m.ToString("N"));;
prints
1,000,000,000.00
999,999,999.00
The reference even has a example for a very large number
In this example, the output is formatted by using the currency format string. Notice that x is rounded because the decimal places exceed $0.99. The variable y, which represents the maximum exact digits, is displayed exactly in the correct format.
public class TestDecimalFormat
{
static void Main()
{
decimal x = 0.999m;
decimal y = 9999999999999999999999999999m;
Console.WriteLine("My amount = {0:C}", x);
Console.WriteLine("Your amount = {0:C}", y);
}
}
/* Output:
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00
*/

Casting Results of Float Multiplication Produces Differing Results if the Float is First Saved to a Variable? [duplicate]

This question already has answers here:
C# Float expression: strange behavior when casting the result float to int
(8 answers)
Closed 6 years ago.
The code here is straight forward but I don't understand the results:
float percent = 0.69f;
int firstInt = (int)(percent*100f);
float tempFloat = percent*100f;
int secondInt = (int)tempFloat;
Debug.Log(firstInt + " " + secondInt);
Why is firstInt 68 but secondInt is 69?
It looks like the compiler has figured out the value of the
percent*100f
expression using double math, and optimized away the computation. This is not allowed when intermediate results are saved in a float variable.
Since .69 does not have anexact representation in float or in double, the two representations "land" on different sides of an int: double is slightly above, while float is slightly below the actual value of .69.

Issue with .equals while comparing double in c# [duplicate]

This question already has answers here:
Comparing double values in C#
(18 answers)
Closed 8 years ago.
I have a float value that i parsed into double later i rounded off to 2.Also i have another float value to which i did exactly the same as first one.
Here is the sample code..
string pulse = arrvaluedline[2].ToString();
pCost = float.Parse(arrvaluedline[3]);
double d = System.Convert.ToDouble(spCost);
double dd = Math.Round(d,2);
string[] arrpulse = pulse.Split(':');
vodanoofPulse = float.Parse(arrpulse[0]);
calculatedCost = CallCost * Pulse;
double dcalcost = Math.Round(calculatedCost, 2);
Now here i am trying to compare
if (dcalcost.Equals(spCost)){
}
Although my both values dcalcost and spCost are 0.4 Except this ,flow is not going inside the if ..Why..Please help me .,
The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .333333 and the Double value returned by dividing 1 by 3 are unequal.
// Initialize two doubles with apparently identical values
double double1 = .33333;
double double2 = 1/3;
// Compare them for equality
Console.WriteLine(double1.Equals(double2)); // displays false
Comparing doubles are not as easy as one might think. Here is an example from MSDN on how you can do it in a better way.
// Initialize two doubles with apparently identical values
double double1 = .333333;
double double2 = (double) 1/3;
// Define the tolerance for variation in their values
double difference = Math.Abs(double1 * .00001);
if (Math.Abs(double1 - double2) <= difference)
Console.WriteLine("double1 and double2 are equal.");
else
Console.WriteLine("double1 and double2 are unequal.");

Finding standard deviation/variance in data values [duplicate]

This question already has answers here:
How do I determine the standard deviation (stddev) of a set of values?
(12 answers)
Closed 9 years ago.
So this is quite a complex problem and I googled alot about it but haven't really come up with anything. So the problem, I need to find the Standard Deviation of some variables within files. So let me state what I need to do: I have the code to find the average value of some numbers extracted from files. What I need to do with that average value is subtract it from the value in the files and then take that new value and square it.
Code to find the average value:
var query5 = from file in fileEntries
doc = XDocument.Load(file)
let x = doc.Descendants("").Single()
let y = doc.Descendants("").Single()
let z = doc.Descendants("")Single()
select new
{
X1 = x.Element("Max").Value,
X2 = x.Element("Min").Value,
Y1 = y.Element("Max").Value,
Y2 = y.Element("Min").Value,
Z1 = z.Element("Max").Value,
Z2 = z.Element("Min").Value
};
Given your above, if you want the population variance and standard deviation, you could do:
// ... code from above
double averageMaximumX = query.Average(t => double.Parse(t.XMax));
double varianceMaximumX = query.Sum(t =>
Math.Pow(double.Parse(t.XMax) - averageMaximumX, 2)));
double stdDevMaximumX = Math.Sqrt(varianceMaximumX);
varianceMaximumX /= query.Count();

Categories