Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.
Is there any built-in .NET framework support to parse these?
No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).
In your case I would just use a switch:
double dblValue;
switch strValue
{
case "-1.#IND":
dblValue = double.Nan;
break;
case "INF":
dblValue = double.Infinity;
break;
//... other casess
default:
dblValue = double.Parse(strValue);
break;
}
NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.
If you have to parse something more special, then just
public double MyParse(string text)
{
if(text == "blablabla")
return double.NaN;
if(text.Contains("blablabla")) ...
if(text.StartsWith(...
return double.Parse(text);
}
Related
when I add price 1.500 in text box and save it, it become 1.5 or 2.350 it's become 2.35 the datatype for the price is decimal (20,3) how can I save the price with the zeros???
If you get the value as a float or a double then when you display it to the user you can decide how you want the value to be represented as a string. For example:
static void Main(string[] args)
{
float value = 1.5f;
string text = string.Format("{0:0.000}", value);
// text = "1.500"
}
Other numeric format strings can be found here:
https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Just add formatting into standard ToString(); in your case you want 3 digits after the decimal point so the corresponding format is F3:
Double value = 2.350;
String result = value.ToString("F3");
decimal value = Math.Round(value, 1, MidpointRounding.AwayFromZero);
Combinig these two responses , you can also write extension method which can serve the purpose.
public enum FormatType
{
Default,
TwoDecimal,
ThreeDecimal,
FourDecimal
}
public static string ToSpecificFormat(this decimal amount, FormatType formatType = FormatType.Default)
{
string fType=string.Empty;
switch (formatType)
{
case FormatType.Default :
fType = "F2";
break;
case FormatType.TwoDecimal :
fType = "F2";
break;
case FormatType.ThreeDecimal:
fType = "F3";
break;
case FormatType.FourDecimal:
fType = "F4";
break;
}
return amount.ToString(fType, CultureInfo.InvariantCulture);
}
You can modify this extension method to an extent you want for culture specific impementation to number format styles to currency, percentage and etc.
I'm trying to found out if a string value is any kind of number. The numbers can be anything like $23.23, (232.3434), 34.4545, 64.345, 34.34%
For dollars and percentages I can remove the % and $ symbols from the string, but I can't get this number to get parsed using this code.
string _number = "64.345";
double _double;
if (Double.TryParse(_number, NumberStyles.Any, null, out _double))
{
}
else
{
}
What am I doing wrong in this code?
What is your culture settings for your OS, it likely is misinterpreting the ..
If you passed in CultureInfo.InvariantCulture instead of null for the format provider that should solve your problem. When you pass in null it uses CultureInfo.CurrentCulture and your PC is set to a culture that does not interpret a . as a separator for decimal numbers.
You could try and use the double.Parse() instead with a try catch statement, like this:
string _number = "64.345";
double _double;
try
{
_double = Double.Parse(_number)
// Other actions
}
catch (FormatException ex)
{
// Actions for when invalid parameter is given for parse
}
I am looking for a function that can check the character if it is a integer and do something is so.
char a = '1';
if (Function(a))
{
do something
}
Use System.Char.IsDigit method
If you want just the pure 0-9 digits, use
if(a>='0' && a<='9')
IsNumeric and IsDigit both return true for some characters outside the 0-9 range:
Difference between Char.IsDigit() and Char.IsNumber() in C#
Integer.TryParse works well.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The bool Char.IsDigit(char c); Method should work perfectly for this instance.
char a = '1';
if (Char.IsDigit(a))
{
//do something
}
Try using System.Char.IsDigit method.
Try Char.IsNumber. Documentation and examples can be found here
It may be better to just use a switch statement. Something like:
switch(a)
{
case '1':
//do something.
break;
case '2':
// do something else.
break;
default: // Not an integer
throw new FormatException();
break;
}
This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:
try
{
Convert.ToInt32("10")
}
catch (FormatException err)
{
// Not an integer, display some error.
}
I have to check the first to characters of a string and if the third character is numeric and do it with MyString.All(char.IsDigit):
if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
Simplest answer:
char chr = '1';
char.isDigit(chr)
I need help figuring out how to assign a string to a double.
double value = "myString";
I have double value = double.Parse("myString"); but this throws a FormatException.
I have trying to concatenate like this:
string stringValue += doubleValue.toString() + intValue.ToString;
return stringValue;
I have double value = double.Parse("myString"); but this throws a string.Format error.
Yes, that's the behaviour you want in this case. "myString" doesn't have a numerical value, so the correct numerical value to give it, is to throw a formatting error.
double.Parse("1.2") would work or not depending on whether the culture in use was one where 1.2 was represented as "1.2" or as "1,2". double.Parse("1.2", CultureInfo.InvariantCulture) will always return 1.2, because it's specific about which culture to use.
double.TryParse is useful where it's likely for someone to pass an inappropriate string (like "myString") because it returns a boolean representing success or failure, rather than throwing an exception.
You can use TryParse
string x = "1234";
double y;
if(double.TryParse(x, out y))
{
Console.WriteLine("success y = " + y.ToString());
}
else
{
Console.WriteLine(x + " could not be converted to a double");
}
Parse it, assuming myString is a valid double string representation (eg "3.49", "1394.293", "-1.30E3")
double value = double.Parse(myString)
Most (All?) of the normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "abc" as a number will throw an exception)
#L.B For custom parsing you can define a NumberFormatInfo like this:
var a = new System.Globalization.NumberFormatInfo()
a.NumberDecimalSeparator = ",";
a.NumberGroupSeparator = ".";
double d = Double.Parse("1.000.000,5", a);
You cannot assign a string to a double. It's impossible. A double is a numerical type. A string is not.
If you parse a string that is a double it is possible.
var doubleThing = Double.Parse("9.99");
double.Parse(string);
Can and will through an exception if the format is incorrect. What are you trying to parse?
double.TryParse("1.05", out value);
Will return true or false if the parse succeeds or fails.
I'm sure this must be simple, but I can't figure out how to word it correctly in Google...
I have a config which has a field:
TimeToPoll="1d"
Now I want to do something like:
TimeSpan.Parse(TimeToPoll);
Returning a timespan of one day.
In C#
EDIT:
I'm looking for a method which allows parse of "1d" as well as "1s" or "1y" etc. Is this possible?
Meaning:
"1d" parses to {1.00:00:00}
"1h" parses to {0.01:00:00}
"1m" parses to {0.00:01:00}
"1s" parses to {0.00:00:01}
This is my resolution:
public static TimeSpan ConvertToTimeSpan(this string timeSpan)
{
var l = timeSpan.Length - 1;
var value = timeSpan.Substring(0, l);
var type = timeSpan.Substring(l, 1);
switch (type)
{
case "d": return TimeSpan.FromDays(double.Parse(value));
case "h": return TimeSpan.FromHours(double.Parse(value));
case "m": return TimeSpan.FromMinutes(double.Parse(value));
case "s": return TimeSpan.FromSeconds(double.Parse(value));
case "f": return TimeSpan.FromMilliseconds(double.Parse(value));
case "z": return TimeSpan.FromTicks(long.Parse(value));
default: return TimeSpan.FromDays(double.Parse(value));
}
}
The d is not needed and is the reason your parse fails.
var oneDay = TimeSpan.Parse("1");
Update:
For what you are looking to do, there is no built in support. You would need to write your own parser.
You should store your values in your config file in one of the formats that TimeSpan.Parse can work with. There are several samples on that page.
EDIT: The examples are in the code toward the bottom of the page.