This might be a very simple question.
Suppose text box show value 10,000.12 when user edits data by mistake he remove first two numbers like ,000.12 and using this textbox in the calculation then it gives an exception. I want a just validate text box.
For Example:
string str = ",100.12;"
Convert to
decimal number = 100.12;
Any Idea?.
It shows only whole number when user remove any thousand separator.
This is pretty messed up and I am not sure if all of you strings will look the same, but in case they do this might do the trick:
string str = ",0,100.12";
decimal number;
bool converted = decimal.TryParse(str.Substring(str.LastIndexOf(",") + 1), out number);
The variable converted will tell you whether or not your string was converted and you will not an exception.
Good luck!
If I understood the question, you want to remove all characters that would prevent the parse routine from failing.
string str = ",0,100.12";
var modified = new StringBuilder();
foreach (char c in str)
{
if (Char.IsDigit(c) || c == '.')
modified.Append(c);
}
decimal number= decimal.Parse(modified.ToString());
string a = "100.12";
decimal b = Convert.ToDecimal(a);
string str = ",0,100.12;";
var newstr = Regex.Replace(str,#"[^\d\.]+","");
decimal d = decimal.Parse(newstr, CultureInfo.InvariantCulture);
Related
I am trying to convert a System.string to a System.double, the input is: He: 4.002602 amu
Code:
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
double i = Convert.ToDouble(data[1]);
I have tried:
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
double i = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
You can use following regular expression without splitting a string which mixed with number and words:
// using System.Text.RegularExpressions
var resultString = Regex.Match(line, #"\d.\d+").Value;
If format of input is something+blank+doubleNumber+blank+something you can use following code:
string line = "He: 4.002602 amu";
int intLspacePos = line.IndexOf(" ") + 1;
int intRspacePos = line.LastIndexOf(" ");
string strNumber = line.Substring(intLspacePos, intRspacePos - intLspacePos);
double dblNumber = Convert.ToDouble(strNumber);
Instead of Convert.ToDouble() use the double.Parse() method, preferably using the invariant culture when the user input is always using a period sign as decimal separator.
So try something like this:
double i = double.Parse(data[1], CultureInfo.InvariantCulture);
EDIT:
I've seen in the screenshot you posted in the comments above that you're not actually checking the contents of data[1] before passing it to the Convert.ToDouble method.
According to MSDN the only case when a FormatException is thrown should be when providing a non-numeric text value (see here). Therefor I'd suggest to add a check for empty strings and null values before, passing the value to the Convert.ToDouble() method. Try updating your code to something like this:
foreach (string line in raw) {
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
if (!string.IsNullOrWhiteSpace(data[1]) {
double i = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
} else {
// Invalid value in data[1]
// Maybe set a breakpoint here and investigate further if necessary
}
}
If this still throws a FormatException then the contents of data[1] must be some non-numeric and non-empty text value, so in that case you should probably check the contents of the data array using the debugger and find out how / why that invalid value got there.
you can convert with specific culture info as below. 2057 is LCID for English (UK).
double i = Convert.ToDouble(data[1], CultureInfo.GetCultureInfo(2057));
I need to extract a variable length decimal number from a string using c# and .NET. The input string is like $PTNTHPR,352.5,N,2.3,N,4.6,N,16*. I need the first occurrence of decimal number, i.e the 352.5 part. The numerical value ranges from 0.0 to 360.0 and I need that number from that string.
I searched a lot and got solution for a fixed length sub string but here I have variable length to extract. I have not tried with any code yet.
If it is always in this format you can use String.Split and decimal.Parse
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var d = decimal.Parse(data.Split(new[]{','})[1]);
Console.WriteLine(d);
This is just a sample code to guide you. You should add additional exception handling logic to this, Also consider using decimal.TryParse
If you want to find the first occurance of decimal value you split the string and parse them one by one.
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var splited = data.Split(new[]{','});
decimal? value = null;
foreach (var part in splited)
{
decimal parsed;
if (decimal.TryParse(part, out parsed))
{
value = parsed;
break;
}
}
Console.WriteLine(value);
First occurence in any of the tokens? Use String.Split to separate them and LINQ to find the first. You can use decimal.TryParse to check if it's parsable:
decimal? firstParsableToken = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".Split(',')
.Select(s => s.TryGetDecimal(NumberFormatInfo.InvariantInfo))
.FirstOrDefault(d => d.HasValue);
Used this simple extension method to parse it to decimal?:
public static decimal? TryGetDecimal(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
decimal d = 0m;
bool success = decimal.TryParse(item, nStyles, formatProvider, out d);
if (success)
return d;
else
return null;
}
If the string is always comma separated, can you not use string.Split() to get each section, then use double.TryParse() to test if that part is numeric?
public static class Helper
{
public static string MyExtract(this string s)
{
return s.Split(',').First(str => Regex.IsMatch(str, #"[0-9.,]"));
}
}
Use it like this: string str = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".MyExtract();
Then convert it to double/decimal if you need it.
Hi all. I have a double number (Ex: 0.000006). I want convert it to string type. But result is "6E-06". I dont want it, i want 0.000006".Thanks you so much
double a = 0.000006;
string resultString = a.toString();
I don't know many number after "." character
It's simple that if you want to show a number as exactly as what it looks, we can cast it to decimal and use the default ToString() like this:
var s = ((decimal)yourNumber).ToString();
//if yourNumber = 0.00000000000000000000000006
//just append the M after it:
var s = (0.00000000000000000000000006M).ToString();
Please check this article and find the format which suits your needs: http://www.csharp-examples.net/string-format-double/
Looks like this one is good enough:
String.Format("{0:0.00}", 123.4567);
Use String.Format() with the format specifier.
double a = 0.000006;
string formatted = String.Format("{0:F6}", a);
Try with the Roundtrip 'R' format specifier:
double a = 0.000006;
string resultString = a.ToString("R");
Double Rate_USD = Convert.ToDouble(txtRateUsd.Text);
string Rate_USD = txtRateUsd.Text;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;
I have a problem with parsing a string to a double. I have a StreamWriter reading lines from a text file. The text file has the following lines:
17-09-2012: (100,98)
17-09-2012: (50,57)
Now, I want to use the values from inside the parantheses, add them together and display them in a textbox. So far I have the following:
int counter = 0;
double res = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("d:\\test.txt");
while ((line = file.ReadLine()) != null)
{
string par = Regex.Match(line, #"\(([^)]*)\)").Value;
double par2 = double.Parse(par);
res += par2;
counter++;
}
file.Close();
textBox1.Text = res.ToString();
However, apparently the input string is not in a correct format, which I find rather odd, since the regex should remove everything but the numbers inside the parantheses. I have even checked for this by writing the string to the textbox without first adding them together, and it showed "100,9850,57". So truly, I do not understand, why it cannot convert the string to a double.
I hope you can tell me, what I am doing wrong.
Your "par" variable is containing a string that looks like: "(100,98)" which is why it's failing to parse.
change your regex to (?<=\()(([^)]*))(?=\))
You can try with - based on InvariantCulture
var culture = CultureInfo.InvariantCulture;
double result = double.Parse(par , culture);
Setting your regex to (?<=\()(([^)]*))(?=\)) and using this helper should solve your problems:
public static double ParseDouble(string input)
{
// unify string (no spaces, only . )
string output = input.Trim().Replace(" ", "").Replace(",", ".");
// split it on points
string[] split = output.Split('.');
if (split.Count() > 1)
{
// take all parts except last
output = String.Join("", split.Take(split.Count() - 1).ToArray());
// combine token parts with last part
output = String.Format("{0}.{1}", output, split.Last());
}
// parse double invariant
double d = Double.Parse(output, CultureInfo.InvariantCulture);
return d;
}
You can force double.Parse to use a culture that uses , as a decimal separator, like this:
CultureInfo culture = new CultureInfo("de-DE");
double d = double.Parse(par, culture);
That's a good idea anyway, if you want your program to work also on computers with different regional settings.
I made it work, by making a try, catch:
string par = Regex.Match(line, #"(?<=\()(([^)]*))(?=\))").Value;
try
{
double par2 = double.Parse(par);
res += par2;
}
catch
{
}
Thanks, everyone for your help.