C# parse value from string - c#

I would like to parse string value like this :
.02234
-.23455
-1.23345
2.
.3
but i get an FormatException
for (int i = 1; i < 7; i++)
{
var item = Double.Parse(reader.ReadLine(44).Substring(8 * i, 8));
richTextBox1.Text += item.ToString() + "\n";
}
the problem that i should convert this numbers like "0.2" or "-.0541" to double or any value type to work with it !!!

Since you've made a comment that , is the decimal separator in your locale, there is a better option than doing a string-replace of . to ,; tell the Double.Parse() method to use a different number format.
See the MSDN doc for Parse(String s). Especially, note the following:
The s parameter is interpreted using
the formatting information in a
NumberFormatInfo object that is
initialized for the current thread
culture. For more information, see
CurrentInfo. To parse a string using
the formatting information of some
other culture, call the
Double.Parse(String, IFormatProvider)
or Double.Parse(String, NumberStyles,
IFormatProvider) method.
Assuming your current thread culture is using a number format that considers , to be the decimal separator (French/France fr-FR, for example), you must pass an IFormatProvider to the Parse() method that defines . as the decimal separator. Conveniently, the "no culture in particular" culture, CultureInfo.InvariantCulture, does just this.
So this code should parse successfully:
for (int i = 1; i < 7; i++)
{
// Assume the substring of ReadLine() contains "-.23455", for example
var item = Double.Parse(reader.ReadLine(44).Substring(8 * i, 8), CultureInfo.InvariantCulture);
richTextBox1.Text += item.ToString() + "\n";
}

You're passing a string that isn't a double, something like 1.a or 1. .3 (1 string representing 2 numbers)
You can use Double.TryParse() and it will not throw an exception but return true/false if it was successful or not. It might make the flow easer.

reader.ReadLine(44).Substring(8 * i, 8).ToString()
You won't need the .ToString(). Verify that this actually returns the value you're looking for.
The format exception is throw because the value it's trying to parse is not valid!
My first guess is that the argument you're passing is not in fact a double.
Might try to split up your calls, and toss in a breakpoint to see what's actually going on.
for (int i = 1; i < 7; i++)
{
string textNum = reader.ReadLine(44).Substring(8 * i, 8);
// add a breakpoint on the next line, then look at textNum. I bet it's not what you hoped.
double item = double.Parse(textNum);
richTextBox1.Text += string.Format("{0}\n", item);
}

Use Double.TryParse() and test to see if the value was successfully parsed into your local variable like this:
for (int i = 1; i < 7; i++)
{
double value = 0;
string input = reader.ReadLine(44).Substring(8 * i, 8);
if (Double.TryParse(input, out value))
{
richTextBox1.Text += value.ToString() + "\n";
}
else
{
richTextBox1.Text = "Invalid double entered.";
}
}

i just find a solution to the problem ( replace to dot with comma ) :
public Double[] GridValues(int fromline)
{
Double[] values = new Double[7];
for (int i = 1; i < 7; i++)
{
string input = ReadLine(fromline).Substring(8 * i, 8).Replace(".", ",");
values[i-1] = double.Parse(input);
}
return values;
}

Related

How can I cut value after point? I mean: double a = 4.33333333 I need print it like this: 4.33?

first I want to apologize for my English, but I have one question: in the code below I want to cut some values after the point, so ho can I do it? BUT Without using any Built methods!
static void Main(string[] args)
{
int[] array = { 6, 2, 3, 2, 12, 1 };
double arithmethicAverage;
arithmethicAverage = ArithmethicAverage(array);
Console.WriteLine($"Arithmetic average of array is: {arithmethicAverage} "); // ==> 4,333333333333333 but i need to print:--> 4,33
}
public static double ArithmethicAverage(int[] array)
{
double result = 0;
for (int i = 0; i < array.Length; i++)
{
result += array[i];
}
result /= array.Length;
return result;
}
If you just want to show it you can use ToString() extension method like this :
arithmethicAverage.ToString("0.00")
For more information you can search about string formatters in C#.
You can use the same format and precision speciriers you'd use in ToString() for example
{arithmethicAverage:N2}
You can specify a custom format string too :
{arithmethicAverage:0.00}
The precision specifier doesn't round :
The precision specifier controls the number of digits in the string representation of a number. It does not round the number itself.
If you don't want to use the built-in methods, this is one of the solutions.
var a = 4.33333333d;
Console.WriteLine(a - a % 0.1); // 4.3
Console.WriteLine(a - a % 0.01); // 4.33
Console.WriteLine(a - a % 0.001); // 4.333
Console.WriteLine(a - a % 0.0001); // 4.3333

C# sum problems

I am using the below code to get the sum of a column in a data grid view.
private void button16_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
}
try
{
decimal tot = 0;
for (int i=0; i <= dataGridView4.RowCount -1; i++)
{
tot += Convert.ToDecimal (dataGridView4.Rows[i].Cells[10].Value);
}
if (tot==0) {}
textBox34.Text = tot.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am getting the error message
Input string was not in a correct format.
ِI found that the problem is in the formatting. Becasue the SQL server data type for that column is money. and the SQL server changes any number I save to this format. 00.0000
For example, If I save 10 SQL server saves it as 10.0000
If I remove the (.) I get no errors.
If I try to sum 10.0000 + 3.0000 it never works out.
Any ideas?
Your problem is that you're trying to convert a value with a decimal point from string to int. When using the money datatype in your DB, the best datatype to use in your code will be the decimal type. See the answer on What is the best data type to use for money in C#
So doing:
int val = Convert.ToInt32("10.00");
Will yield the following error (which is what you're receiving):
Unhandled Exception: System.FormatException: Input string was not in a
correct format.
You can convert the value using the Convert.ToDecimal() method:
decimal val = Convert.ToDecimal("10.00");
If you want to remove the decimal portion of the value, you can use one of the following methods based on your requirements:
Math.Floor
Math.Ceiling
Math.Round
Math.Truncate
For example:
decimal val2 = Math.Round(val);
Or:
decimal val2 = Math.Truncate(val);
If you simply want to return the value as a string but without the decimal portion, you can do as follows:
decimal val = Convert.ToDecimal("10.00");
Console.WriteLine(val.ToString("0.#"));
Edit:
So in your code, change:
int sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
}
For:
decimal sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToDecimal(dataGridView4.Rows[i].Cells[10].Value);
}

How to format floating point value with fix number of digits?

Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?
Say I wish 6 digits, I want to have these results:
0.00123456789 gives "0.00123"
1.23456789 gives "1.23457"
123.456789 gives "123.457"
0.0000000123456789 gives "0.00000"
12345678.9 gives "12345679" (on overflow I want to see all digits left of decimalpoint)
4.2 gives "4.20000"
I'm experimenting with double.ToString, but cannot find any suitable format string.
Already tried "G6" (gives sometimes exponential format), "F6" (comes close, but 0.123456789 gives "0.123457" which are 7 digits).
I think some of your examples are wrong.
But I still think that I understand what you want to achieve.
I made an extension method.
public static class StringExtensionMethods
{
public static string ToString(this double d, int numberOfDigits)
{
var result = "";
// Split the number.
// Delimiter can vary depending on locale, should consider this and not use "."
string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
if(split[0].Count() >= numberOfDigits)
{
result = split[0].Substring(0, numberOfDigits);
}
else
{
result = split[0];
result += ".";
result += split[1];
// Add padding.
while(result.Count() < numberOfDigits +1)
result += "0";
result = result.Substring(0, numberOfDigits + 1);
}
return result;
}
}
I ran it with your examples:
double d0 = 0.00123456789;
double d1 = 1.23456789;
double d2 = 123.456789;
double d3 = 0.0000000123456789;
double d4 = 12345678.9;
double d5 = 4.2;
Console.WriteLine(d0.ToString(6));
Console.WriteLine(d1.ToString(6));
Console.WriteLine(d2.ToString(6));
Console.WriteLine(d3.ToString(6));
Console.WriteLine(d4.ToString(6));
Console.WriteLine(d5.ToString(6));
This is the output:
0.00123
1.23456
123.456
1.23456
123456
4.20000
I don't think this is the best way to solve it, but I like extension methods.
DoubleConverter class: http://1drv.ms/1yEbvL4
If your goal is to avoid "jumping" of the decimal point:
Use g formating, this does the most sensible thing to do
See where the decimal point is in your resulting string
pad with spaces at the beginning to align the column at the decimal point
As I understand, there is no predefined format that does what I need. So for everyone who is interested, here is the function I ended up with:
public string FormatValue(double d, int noOfDigits)
{
double abs = Math.Abs(d);
int left = abs < 1 ? 1 : (int)(Math.Log10(abs) + 1);
int usedDigits = 0;
StringBuilder sb = new StringBuilder();
for(; usedDigits < left; usedDigits++)
{
sb.Append("0");
}
if(usedDigits < noOfDigits)
{
sb.Append(".");
for(; usedDigits < noOfDigits; usedDigits++)
{
sb.Append("0");
}
}
return d.ToString(sb.ToString());
}

String/Int to double with precision defined onruntime

I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}

Converting number to comma separated values

I need to convert numbers into a comma separated format to display in C#.
For Example:
1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000
How to achieve this in C#?
I tried the below code:
int number = 1000;
number.ToString("#,##0");
But it is not working for lakhs.
I guess you can do this by creating a custom number format info for your needs
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";
Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000
if specifically only for numbers then you could also do
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
Console.WriteLine(15000000.ToString("N0", nfo));
Here's a similar thread to yours add commas in thousands place for a number
and here's the solution that worked perfectly for me
String.Format("{0:n}", 1234);
String.Format("{0:n0}", 9876); // no decimals
If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.
public static string CommaInt(int Number,int Comma)
{
string IntegerNumber = Number.ToString();
string output="";
int q = IntegerNumber.Length % Comma;
int x = q==0?Comma:q;
int i = -1;
foreach (char y in IntegerNumber)
{
i++;
if (i == x) output += "," + y;
else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
else output += y;
}
return output;
}
Have you tried:
ToString("#,##0.00")
Quick and dirty way:
Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);
An easy solution would be to pass a format into the ToString() method:
string format = "$#,##0.00;-$#,##0.00;Zero";
decimal positiveMoney = 24508975.94m;
decimal negativeMoney = -34.78m;
decimal zeroMoney = 0m;
positiveMoney.ToString(format); //will return $24,508,975.94
negativeMoney.ToString(format); //will return -$34.78
zeroMoney.ToString(format); //will return Zero
Hope this helps,

Categories