Parse any string number to number - c#

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
}

Related

Normalize a string which contains a decimal to specific CultureInfo.NumberFormat

I'm struggling trying to normalize a number to an specific CultureInfo, applying its NumberFormat
Let's say I have a string which also contains some characters, so I need to clean it up:
var cleanedInput = Regex.Replace(userInput, #"[^0-9-,'.]+", "");
So I'm basically keeping , ' and . . I'm doing this because depending on the CultureInfo, the , and the . are differently used to separate decimals or to group the numbers.
Having that in mind, I apply the Decimal.TryParse method, specifying the NumberStyle to allow decimals and the IFormatProvideris going to be dinamically applied to the desired "local" CultureInfo.NumberFormat.
decimal numericData;
if (!decimal.TryParse(cleanedInput, NumberStyles.AllowDecimalPoint, LocaleUser.NumberFormat, out numericData))
throw new Exception($"Error occurred. Could not parse:{cleanedInput} ");
Let's say we input "hi9000,99hi". Once cleaned, we get "9000,99". Nice.
So then, we apply the TryParse and it returns Decimal 9000.99. Important saying that I'm actually applying the es-ES CultureInfo which has the , as decimal separator. I'm basically expecting 9000,99 or 9.000,99 .
The code is not raising the Exception, but looks like it's not applying the CultureInfo I specified.
What am I exactly missing? I have the feeling that Decimal.TryParse is a swiss army knife that I'm handling well.
Many thanks in advance.
Using double.Parse, decimal.Parse or decimal.TryParse seems to work. How was the CultureInfo defined?
string value = "9000,99";
decimal number;
CultureInfo culture = CultureInfo.CreateSpecificCulture("es-ES");
try {
number = decimal.Parse(value, culture);
decimal.TryParse(value, NumberStyles.Any, culture, out decimal num);
Console.WriteLine($"{culture.Name}: {value} = {number} / {num}");
} catch (FormatException) {
Console.WriteLine($"{culture.Name}: Unable to parse [{value}]");
}
Output:
es-ES: 9000,99 = 9000.99 / 9000.99
So, given that a Decimal will always be a Decimal and has no format, as on the comments has been stated, I was incorrectly focusing the questions and what was I searching for!
I'm finally using this method:
private decimal CleanUserInput(string userInput, CultureInfo localeUser)
{
if (localeUser == null)
throw new Exception("A CultureInfo must be specified. ");
var cleanedInput = Regex.Replace(userInput, #"[^0-9-,\.']+", "");
if (string.IsNullOrWhiteSpace(cleanedInput))
throw new Exception("Data provided has no numbers to be parsed. ");
decimal numericData;
if (!decimal.TryParse(cleanedInput, NumberStyles.Any, localeUser, out numericData))
throw new Exception($"Couldn't parse {cleanedInput} . Make sure the applied CultureInfo ({LocaleUser.DisplayName}) is the correct one. Decimal separator to be applied: <{LocaleUser.NumberFormat.NumberDecimalSeparator}> Numeric group separator to be applied: <{LocaleUser.NumberFormat.NumberGroupSeparator}>");
return numericData;
}

C# - can I parse back text that have already formatted to currency?

this is function to format text that contains numbers only into $ currency
private String GLOBALIZE_TEXT(String originalText)
{
decimal parsed;
CultureInfo myCultureInfo;
string formattedText = "";
//use try catch to prevent larger inputs
try
{
parsed = decimal.Parse(originalText, CultureInfo.InvariantCulture);
myCultureInfo = new CultureInfo("$");
formattedText = string.Format(myCultureInfo, "{0:c}", parsed);
}
catch (Exception ignorethis)
{
}
return formattedText;
}
now in usage:
String myString = "3821";
myString = GLOBALIZE_TEXT(myString);
//now my String becomes "$3,821.00"
question is, can I parse back that "$3,821.00" to "3821" again?
I need to parse it back so I can use it as an integer where "3821" can be converted by Convert.ToInt32("3821").
or maybe that parsed String can also be converted directly to string?
Please let me know your opinion.
You can try:
double.Parse(myString, NumberStyles.Currency);
More information on the NumberStyles enum can be found on MSDN here and more information on this specific double.Parse method can be found on MSDN here.
Maybe it's best to ask why you need to do this? You should always try and store a value in it's native format. If you need to do it from a captured or imported string then I would go the route of using a regular expression to remove it.
Regular expression to remove any currency symbol from a string?

Input string was not in a correct format

I want to store result of total & tempDiscRs into b1..while storing it throws the error that Input string was not in correct format
decimal b1 = Convert.ToDecimal(lblDisRate.Text);
b1 = total * tempDiscRs;
decimal myValue;
if(Decimal.TryParse(lblDisRate.Text, out myValue))
{
//correct
}
else
{
//wrong
}
See more about Decimal.TryParse Method
You should be aware of the culture you're in.
Example: In US, the comma separator is a dot (.) while in Germany it is a comma (,).
Try
lblDisRate.Text.ToString(System.Globalization.CultureInfo.InvariantCulture)
In order to use Invariant Culture so you always use a dot instead of a comma.

Input string was not in a correct format. calling TimeSpan.FromSeconds(Convert.ToDouble(time)) in IE on Changing Culture

Hi i m using given below method to convert in to string its working fine chrome but in IE its through exception Input string was not in a correct format. at this line
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
these are values i m passing to it
600, 298.8, 65505, 69, 70, 20.5, 20.5, 20.5, 20.5, 1840.4, 682, 1040.3
in chrome its working but in IE it gives exception on second value when i change the culture to french language please help me out what is the problem
public static String ConvertTimeToString(this string time)
{
if (String.IsNullOrEmpty(time))
{
return time;
}
TimeSpan s;
if (time.IndexOf(':') >= 0)
{
s = TimeSpan.Parse(time);
}
else
{
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
}
return s.ConvertTimeToString();
}
The failure is probably in the call Convert.ToDouble. Your code probably executes in a CultureInfo that has ',' as decimal separator, but your values use '.'. I would advice you to use Double.TryParse using a CultureInfo that has '.' as decimal separator instead:
Double value;
if (Double.TryParse(time, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out value))
{
s = TimeSpan.FromSeconds(value);
}
You need to specify an IFormatProvider when you use Convert.ToDouble(time):
Convert.ToDouble(time, CultureInfo.InvariantCulture)
Specifying CulturInfo.InvariantCulture specifies a culture that expect floating points written as 1.234 (note the period). The source of your problem may be that you time is in the format 1,234 (note the comma). Or maybe it is the reverse: You don't specify an IFormatProvider and the current culture of you ASP.NET process uses comma as a decimal separator, but the string provided uses period?
If the decimal point used isn't consistent you should either fix it at the source (not sure what the source is here) or as a last resort you can replace comma by period:
Convert.ToDouble(time.Replace(",", ".") , CultureInfo.InvariantCulture)
However, trying to parse a string and not knowing the what to expect is not the best thing to do.

C# How to assign a string to a double

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.

Categories