Compare comma and point(dot) in decimal separator - c#

Can someone help me?
I'm not sure whether it is ignorance or lack of knowledge, but it's really annoying.
What the best way compare this decimal format 123.456,22 and 123,456.22.
i try this way :
decimal val1 = 0; decimal val2 = 0;
decimal.TryParse("123,456.22", out val1);
decimal.TryParse("123.456,22", out val2);
if the computer have 123.456,22 format,
i try decimal.TryParse(123,456.22, out val1) --> val1 = 0;
now i am using code : Split by "," or "." , i just wondering what easier way to do that.

Use the Decimal.Parse method: http://msdn.microsoft.com/en-us/library/cafs243z.aspx
Decimal.Parse(value);
You can use the overloaded method to pass in the Culture (http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx)
Decimal.Parse(value, new CultureInfo("en-GB"));

Try this:
decimal d1;
string s1 = "123,456.22";
if (Decimal.TryParse(s1,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.GetCultureInfo("ro-RO"),
out d1))
{
Console.WriteLine("Success: {0} converted into {1} using the ro-RO number format",
s1, d1);
}
else if (Decimal.TryParse(s1, out d1))
{
Console.WriteLine("Success: {0} converted into {1} using the {2} number format",
s1, d1,System.Globalization.CultureInfo.CurrentCulture.Name);
}
}
}
You might find this Wikipedia article interesting: Decimal mark.

123.456,22 and 123,456.22 have a different separator, while in one case its point(.) in the other case its a comma(,) when you just use Parse it would rely on the current culture, so one of them would fail the parse.
In such case you should build up the relevant NumberFormatInfo and set it as per your needs for the decimal separator(NumberDecimalSeparator) and the thousands separator(NumberGroupSeparator)
So you should use TryParse and if that returns false then build your custom one like this and make it available to the Parse as Parameter.
// check with TryParse first and if it returns false then try as below
NumberFormatInfo numinf = new NumberFormatInfo();
numinf.NumberDecimalSeparator= ",";
numinf.NumberGroupSeparator= ".";
decimal.Parse("your failed tryparse", numinf);

decimal d1;
string s1 = "123,456.22";
if (Decimal.TryParse(s1,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.GetCultureInfo("ro-RO"),
out d1))
{
Console.WriteLine("Success: {0} converted into {1} using the ro-RO number format",
s1, d1);
}
else if (Decimal.TryParse(s1, out d1))
{
Console.WriteLine("Success: {0} converted into {1} using the {2} number format",
s1, d1,System.Globalization.CultureInfo.CurrentCulture.Name);
}
}
}
can be used only on console application??

Related

Converting to decimal returns the numbers concated [duplicate]

I want to parse a string like "3.5" to a double. However,
double.Parse("3.5")
yields 35 and
double.Parse("3.5", System.Globalization.NumberStyles.AllowDecimalPoint)
throws a FormatException.
Now my computer's locale is set to German, wherein a comma is used as decimal separator. It might have to do something with that and double.Parse() expecting "3,5" as input, but I'm not sure.
How can I parse a string containing a decimal number that may or may not be formatted as specified in my current locale?
double.Parse("3.5", CultureInfo.InvariantCulture)
I usualy use a multi-culture function to parse user input, mostly because if someone is used to the numpad and is using a culture that use a comma as the decimal separator, that person will use the point of the numpad instead of a comma.
public static double GetDouble(string value, double defaultValue)
{
double result;
//Try parsing in the current culture
if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
//Then try in US english
!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
//Then in neutral language
!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
{
result = defaultValue;
}
return result;
}
Beware though, #nikie comments are true. To my defense, I use this function in a controlled environment where I know that the culture can either be en-US, en-CA or fr-CA. I use this function because in French, we use the comma as a decimal separator, but anybody who ever worked in finance will always use the decimal separator on the numpad, but this is a point, not a comma. So even in the fr-CA culture, I need to parse number that will have a point as the decimal separator.
I couldn't write a comment, so I write here:
double.Parse("3.5", CultureInfo.InvariantCulture) is not a good idea, because in Canada we write 3,5 instead of 3.5 and this function gives us 35 as a result.
I tested both on my computer:
double.Parse("3.5", CultureInfo.InvariantCulture) --> 3.5 OK
double.Parse("3,5", CultureInfo.InvariantCulture) --> 35 not OK
This is a correct way that Pierre-Alain Vigeant mentioned
public static double GetDouble(string value, double defaultValue)
{
double result;
// Try parsing in the current culture
if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
// Then try in US english
!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
// Then in neutral language
!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
{
result = defaultValue;
}
return result;
}
Double.Parse("3,5".Replace(',', '.'), CultureInfo.InvariantCulture)
Replace the comma with a point before parsing. Useful in countries with a comma as decimal separator. Think about limiting user input (if necessary) to one comma or point.
Look, every answer above that proposes writing a string replacement by a constant string can only be wrong. Why? Because you don't respect the region settings of Windows! Windows assures the user to have the freedom to set whatever separator character s/he wants. S/He can open up the control panel, go into the region panel, click on advanced and change the character at any time. Even during your program run. Think of this. A good solution must be aware of this.
So, first you will have to ask yourself, where this number is coming from, that you want to parse. If it's coming from input in the .NET Framework no problem, because it will be in the same format. But maybe it was coming from outside, maybe from a external server, maybe from an old DB that only supports string properties. There, the db admin should have given a rule in which format the numbers are to be stored. If you know for example that it will be an US DB with US format you can use this piece of code:
CultureInfo usCulture = new CultureInfo("en-US");
NumberFormatInfo dbNumberFormat = usCulture.NumberFormat;
decimal number = decimal.Parse(db.numberString, dbNumberFormat);
This will work fine anywhere on the world. And please don't use 'Convert.ToXxxx'. The 'Convert' class is thought only as a base for conversions in any direction. Besides: You may use the similar mechanism for DateTimes too.
The trick is to use invariant culture, to parse dot in all cultures.
double.Parse("3.5", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);
string testString1 = "2,457";
string testString2 = "2.457";
double testNum = 0.5;
char decimalSepparator;
decimalSepparator = testNum.ToString()[1];
Console.WriteLine(double.Parse(testString1.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
Console.WriteLine(double.Parse(testString2.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
My two cents on this topic, trying to provide a generic, double conversion method:
private static double ParseDouble(object value)
{
double result;
string doubleAsString = value.ToString();
IEnumerable<char> doubleAsCharList = doubleAsString.ToList();
if (doubleAsCharList.Where(ch => ch == '.' || ch == ',').Count() <= 1)
{
double.TryParse(doubleAsString.Replace(',', '.'),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else
{
if (doubleAsCharList.Where(ch => ch == '.').Count() <= 1
&& doubleAsCharList.Where(ch => ch == ',').Count() > 1)
{
double.TryParse(doubleAsString.Replace(",", string.Empty),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else if (doubleAsCharList.Where(ch => ch == ',').Count() <= 1
&& doubleAsCharList.Where(ch => ch == '.').Count() > 1)
{
double.TryParse(doubleAsString.Replace(".", string.Empty).Replace(',', '.'),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else
{
throw new ParsingException($"Error parsing {doubleAsString} as double, try removing thousand separators (if any)");
}
}
return result;
}
Works as expected with:
1.1
1,1
1,000,000,000
1.000.000.000
1,000,000,000.99
1.000.000.000,99
5,000,111.3
5.000.111,3
0.99,000,111,88
0,99.000.111.88
No default conversion is implemented, so it would fail trying to parse 1.3,14, 1,3.14 or similar cases.
The following code does the job in any scenario. It's a little bit parsing.
List<string> inputs = new List<string>()
{
"1.234.567,89",
"1 234 567,89",
"1 234 567.89",
"1,234,567.89",
"123456789",
"1234567,89",
"1234567.89",
};
string output;
foreach (string input in inputs)
{
// Unify string (no spaces, only .)
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);
Console.WriteLine(d);
}
I think 100% correct conversion isn't possible, if the value comes from a user input. e.g. if the value is 123.456, it can be a grouping or it can be a decimal point. If you really need 100% you have to describe your format and throw an exception if it is not correct.
But I improved the code of JanW, so we get a little bit more ahead to the 100%. The idea behind is, that if the last separator is a groupSeperator, this would be more an integer type, than a double.
The added code is in the first if of GetDouble.
void Main()
{
List<string> inputs = new List<string>() {
"1.234.567,89",
"1 234 567,89",
"1 234 567.89",
"1,234,567.89",
"1234567,89",
"1234567.89",
"123456789",
"123.456.789",
"123,456,789,"
};
foreach(string input in inputs) {
Console.WriteLine(GetDouble(input,0d));
}
}
public static double GetDouble(string value, double defaultValue) {
double result;
string output;
// Check if last seperator==groupSeperator
string groupSep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
if (value.LastIndexOf(groupSep) + 4 == value.Count())
{
bool tryParse = double.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out result);
result = tryParse ? result : defaultValue;
}
else
{
// Unify string (no spaces, only . )
output = value.Trim().Replace(" ", string.Empty).Replace(",", ".");
// Split it on points
string[] split = output.Split('.');
if (split.Count() > 1)
{
// Take all parts except last
output = string.Join(string.Empty, split.Take(split.Count()-1).ToArray());
// Combine token parts with last part
output = string.Format("{0}.{1}", output, split.Last());
}
// Parse double invariant
result = double.Parse(output, System.Globalization.CultureInfo.InvariantCulture);
}
return result;
}
var doublePattern = #"(?<integer>[0-9]+)(?:\,|\.)(?<fraction>[0-9]+)";
var sourceDoubleString = "03444,44426";
var match = Regex.Match(sourceDoubleString, doublePattern);
var doubleResult = match.Success ? double.Parse(match.Groups["integer"].Value) + (match.Groups["fraction"].Value == null ? 0 : double.Parse(match.Groups["fraction"].Value) / Math.Pow(10, match.Groups["fraction"].Value.Length)): 0;
Console.WriteLine("Double of string '{0}' is {1}", sourceDoubleString, doubleResult);
Instead of having to specify a locale in all parses, I prefer to set an application wide locale, although if string formats are not consistent across the app, this might not work.
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-PT");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-PT");
Defining this at the begining of your application will make all double parses expect a comma as the decimal delimiter. You can set an appropriate locale so that the decimal and thousands separator fits the strings you are parsing.
It's difficult without specifying what decimal separator to look for, but if you do, this is what I'm using:
public static double Parse(string str, char decimalSep)
{
string s = GetInvariantParseString(str, decimalSep);
return double.Parse(s, System.Globalization.CultureInfo.InvariantCulture);
}
public static bool TryParse(string str, char decimalSep, out double result)
{
// NumberStyles.Float | NumberStyles.AllowThousands got from Reflector
return double.TryParse(GetInvariantParseString(str, decimalSep), NumberStyles.Float | NumberStyles.AllowThousands, System.Globalization.CultureInfo.InvariantCulture, out result);
}
private static string GetInvariantParseString(string str, char decimalSep)
{
str = str.Replace(" ", "");
if (decimalSep != '.')
str = SwapChar(str, decimalSep, '.');
return str;
}
public static string SwapChar(string value, char from, char to)
{
if (value == null)
throw new ArgumentNullException("value");
StringBuilder builder = new StringBuilder();
foreach (var item in value)
{
char c = item;
if (c == from)
c = to;
else if (c == to)
c = from;
builder.Append(c);
}
return builder.ToString();
}
private static void ParseTestErr(string p, char p_2)
{
double res;
bool b = TryParse(p, p_2, out res);
if (b)
throw new Exception();
}
private static void ParseTest(double p, string p_2, char p_3)
{
double d = Parse(p_2, p_3);
if (d != p)
throw new Exception();
}
static void Main(string[] args)
{
ParseTest(100100100.100, "100.100.100,100", ',');
ParseTest(100100100.100, "100,100,100.100", '.');
ParseTest(100100100100, "100.100.100.100", ',');
ParseTest(100100100100, "100,100,100,100", '.');
ParseTestErr("100,100,100,100", ',');
ParseTestErr("100.100.100.100", '.');
ParseTest(100100100100, "100 100 100 100.0", '.');
ParseTest(100100100.100, "100 100 100.100", '.');
ParseTest(100100100.100, "100 100 100,100", ',');
ParseTest(100100100100, "100 100 100,100", '.');
ParseTest(1234567.89, "1.234.567,89", ',');
ParseTest(1234567.89, "1 234 567,89", ',');
ParseTest(1234567.89, "1 234 567.89", '.');
ParseTest(1234567.89, "1,234,567.89", '.');
ParseTest(1234567.89, "1234567,89", ',');
ParseTest(1234567.89, "1234567.89", '.');
ParseTest(123456789, "123456789", '.');
ParseTest(123456789, "123456789", ',');
ParseTest(123456789, "123.456.789", ',');
ParseTest(1234567890, "1.234.567.890", ',');
}
This should work with any culture. It correctly fails to parse strings that has more than one decimal separator, unlike implementations that replace instead of swap.
I improved the code of #JanW as well...
I need it to format results from medical instruments, and they also send ">1000", "23.3e02", "350E-02", and "NEGATIVE".
private string FormatResult(string vResult)
{
string output;
string input = vResult;
// Unify string (no spaces, only .)
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());
}
string sfirst = output.Substring(0, 1);
try
{
if (sfirst == "<" || sfirst == ">")
{
output = output.Replace(sfirst, "");
double res = Double.Parse(output);
return String.Format("{1}{0:0.####}", res, sfirst);
}
else
{
double res = Double.Parse(output);
return String.Format("{0:0.####}", res);
}
}
catch
{
return output;
}
}
Here is a solution that handles any number string that many include commas and periods. This solution is particular for money amounts so only the tenths and hundredths place are expected. Anything more is treated as a whole number.
First remove anything that is not a number, comma, period, or negative sign.
string stringAmount = Regex.Replace(originalString, #"[^0-9\.\-,]", "");
Then we split up the number into the whole number and decimal number.
string[] decimalParsed = Regex.Split(stringAmount, #"(?:\.|,)(?=\d{2}$)");
(This Regex expression selects a comma or period that is two numbers from the end of the string.)
Now we take the whole number and strip it of any commas and periods.
string wholeAmount = decimalParsed[0].Replace(",", "").Replace(".", "");
if (wholeAmount.IsNullOrEmpty())
wholeAmount = "0";
Now we handle the decimal part, if any.
string decimalAmount = "00";
if (decimalParsed.Length == 2)
{
decimalAmount = decimalParsed[1];
}
Finally we can put the whole and decimal together and parse the Double.
double amount = $"{wholeAmount}.{decimalAmount}".ToDouble();
This will handle 200,00, 1 000,00 , 1,000 , 1.000,33 , 2,000.000,78 etc.
I am developing a .Net Maui app that runs on Windows, Mac, Android, and iPhone. I have 3 double values that I parse and store using '.' (e.g. "32.5") in all cases: latitude, longitude, and altitude. I happen to have the Android and iPhone set for Spanish and noticed that the Android parsed the '.' string just fine. However, the iPhone refused to parse it correctly unless I substituted ',' for the '.'. Otherwise, the result was always a huge number.
Rather than deal with the complications of localization, I came up with a simple solution that takes advantage of the specific limits of my double numbers.
case "Lat":
waypoint.Lat = ParseDouble(xmlVal, 90);
break;
case "Lon":
waypoint.Lon = ParseDouble(xmlVal, 180);
break;
case "Alt":
waypoint.Alt = ParseDouble(xmlVal, 32000);
public static double ParseDouble(string val, double limit)
{
double result;
if (double.TryParse(val, out result))
{
if (Math.Abs(result) <= limit)
return result;
else if (double.TryParse(val.Replace('.', ','), out result))
{
if (Math.Abs(result) <= limit)
return result;
}
}
return 0;
}
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentCulture;
string _pos = dblstr.Replace(".",
ci.NumberFormat.NumberDecimalSeparator).Replace(",",
ci.NumberFormat.NumberDecimalSeparator);
double _dbl = double.Parse(_pos);
The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.
double val;
if (temp.Text.Split('.').Length > 1)
{
val = double.Parse(temp.Text.Split('.')[0]);
if (temp.Text.Split('.')[1].Length == 1)
val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
else
val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
}
else
val = double.Parse(RR(temp.Text));
Multiply the number and then divide it by what you multiplied it by before.
For example,
perc = double.Parse("3.555)*1000;
result = perc/1000

Why does C# TryParse not handle NaN?

I have some common methods for parsing with default value overrides when reading in some old Fortran data. Occasionally the data has NaN (Not a number) where there should be a numeric value. I expected that the TryParse would see the string "NaN" and fail to parse. However, TryParse successfully parses and places NaN in for the numeric value. Is this expected behavior? If this is expected, are there any other "gotcha" values that I should be looking for?
public static double GetDoubleFromString(string s, double defaultOnFailure = 0)
{
//Must be here due to TryParse returning NaN to d and result is set to true below
if (s.Contains("NaN"))
{
log.Warn(string.Format("String contained NaN, returning defaultOnFailure {0} string was {1}", defaultOnFailure, s));
return defaultOnFailure;
}
var d = defaultOnFailure;
if (!double.TryParse(s.Trim(), out d))
{
log.Warn(string.Format("Failed to parse double from string returning defaultOnFailure {0} string was {1}", defaultOnFailure, s));
}
return d;
}
UPDATE
I feel that it should be mentioned, that this only happens for double, long and int do not return the NaN value. See the example code below, the Common.... code is just formatted Console.WriteLine or stops for console execution. See screenshot below for output.
public static void NanTestMain()
{
Common.WriteBlankWithTitle("Test parse NaN");
string s = "NaN";
Common.WriteBlankWithTitle("NaN to Int");
int i;
var intSuccess = int.TryParse(s, out i);
Console.WriteLine(string.Format("Int parse of {0} parse = {1}", i, intSuccess));
Common.WriteBlankWithTitle("NaN to Double");
double d;
var doubleSuccess = double.TryParse(s, out d);
Console.WriteLine(string.Format("Double parse of {0} parse = {1}", d, doubleSuccess));
Common.WriteBlankWithTitle("NaN to Long");
long l;
var longSuccess = long.TryParse(s, out l);
Console.WriteLine(string.Format("Long parse of {0} parse = {1}", l, longSuccess));
Common.Pause();
}
From MSDN:
The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture indicated by provider.
There are three "special" values to look out for. However, the last few words are key - depending on the current culture, you might see something other than "NaN"!
Double.NaN is a valid value for a double, so this is normal.
There is also negative and positive infinity. Check here for other possible 'special' values.

Convert string to decimal but keep numeric portion

Is there a way to convert a string to decimal in C# but ignoring trailing "garbage"? i.e. like PHP's floatval() or C strtod() ?
e.g.
Convert string "2974.23abcdefs" to decimal 2974.23
As others have mentioned, there is no exact, like for like, replacement for what you can do in PHP and I think, for good reason. In the scenario of a web application, I'm not really sure that if I were accepting a decimal with garbage at the end, I'd actually want to consider that as valid data but this is just my opinion.
What you can do is define a regular expression that would capture the decimal and recognise that this is happening. I find this much safer and reliable.
Obviously, the regular expression can be improved but this is a simple example for you: -
var match = Regex.Match("2974.23abcdefs", "^([0-9]+\\.[0-9]+)(.+)?$");
if (match.Success)
{
// See the also the link below for using Decimal.TryParse
Console.WriteLine(Convert.ToDecimal(match.Groups[1].Value));
}
See https://msdn.microsoft.com/en-us/library/system.decimal.tryparse%28v=vs.110%29.aspx for my preferred way to convert to a decimal. This would ensure that you are coping with the output of the regular expression for how Decimal is comprised
For more information on regular expressions, see https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=vs.110%29.aspx
This works but only takes care of digits and the current culture's decimal-separator:
string input = "2974.23abcdefs";
decimal d;
char decSep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0]; // there is no culture with a decimal-separator that has more than one letter so this isn't harmful
if(!string.IsNullOrEmpty(input) && Char.IsDigit(input[0]))
{
string number = string.Concat(input.TakeWhile(c => Char.IsDigit(c) || decSep == c));
bool validDecimal = decimal.TryParse(number, out d);
Console.WriteLine("Valid? {0} Parsed to: {1}", validDecimal, d);
}
Since we are using , as decimal separator here in germany i get a different result than people who use . as separator. You get 2974.23 and i get 2974.
As a first, second, third try, this should go:
static double Parse(string str, IFormatProvider provider = null)
{
if (str == string.Empty)
{
return 0;
}
if (provider == null)
{
provider = CultureInfo.CurrentCulture;
}
NumberFormatInfo nfi = NumberFormatInfo.GetInstance(provider);
// [ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
string ws = #"\s*";
string sign = #"(" + Regex.Escape(nfi.PositiveSign) + "|" + Regex.Escape(nfi.NegativeSign) + ")?";
string integralDigits1 = "([0-9](" + Regex.Escape(nfi.NumberGroupSeparator) + ")*)*";
string integralDigits2 = "[0-9]+";
string fractionalDigits = "(" + Regex.Escape(nfi.NumberDecimalSeparator) + "[0-9]*)?";
string exponentialDigits = "([Ee]" + sign + "[0-9]+)?";
var rx = new Regex(ws + sign + integralDigits1 + integralDigits2 + fractionalDigits + exponentialDigits);
string match = rx.Match(str).ToString();
if (match == string.Empty)
{
return 0;
}
return double.Parse(match, provider);
}
Note that the composed regex is very complex, because there are various "parts" in a full double that has been written to a string.
From MSDN:
[ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
Still some numbers will crash this function, if they are too much big. So passing new string('9', 1000) will make the double.Parse throw an exception.
Use it like:
double num = Parse(" +1,0.1234E+12abcdefgh", CultureInfo.InvariantCulture);
or
double num = Parse(" +1,,,,,0.1234E+12abcdefgh");
(if you don't need to configure the culture, will use the CultureInfo.CurrentCulture)
There are many ways to do so. I suggest using a Regex first, and then decimal.TryParse().
This is a regex that grabs a floating point number at the begin of the string, like -123.43 or just 1234.56 or 123456:
^([+-][0-9]+\.?[0-9]*).*$
Putting this into C# looks like this:
// Step 1: Getting some input
String input = "123.4533wefwe";
// Step 2: Get rid of the trail
Regex r = new Regex(#"^([+-][0-9]+\.?[0-9]*).*$", RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(input);
if (matches.Count > 0) {
Match match = matches[0];
GroupCollection groups = match.Groups;
// Step 3: create a real decimal from the string
decimal i;
NumberStyles style;
CultureInfo culture;
style = NumberStyles.Number;
culture = CultureInfo.CreateSpecificCulture("en-GB");
String matchedNumber = groups[1].Value;
if (decimal.TryParse(matchedNumber, style, culture, out i)) {
// Step 4: giving back the result:
Console.WriteLine("Parsed decimal: " + i);
}
}
The output of this is:
Parsed decimal: 123.4533
Remark: All this seems to become a bigger problem if you would like to parse real floating point number literals that include exponential notation. Then, severals stages of casting would be necessary.

string to double parsing error

i have the following code:
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("mk-MK");
string s2 = "4.434,00";
double d;
if (Double.TryParse(s2, NumberStyles.Number, CultureInfo.CurrentCulture, out d))
{
//String.Format("{0:0.0,00}", d);
Console.WriteLine(d + " Type of: " + d.GetType());
}
else
{
Console.WriteLine("ne go parsirashe");
}
String.Format("{0:0.0,00}", d);
Console.WriteLine(d);
//Console.WriteLine(String.Format("{0:0,0.00}", d));
//Console.WriteLine(s2.GetType().ToString());
//Console.ReadLine();
//String.Format("{0:0.0,00}"
Console.ReadLine();
The output is: 4434 Type of: System.Double
4434
Why isn't the value of d in the format of : 4.434,00 ? Can you please help me with this? I've sent couple of hours trying to figure this out before trying to reach out to you guys. Thanks!!!
You are discarding your formatted string - you are not assigning it to a string and simply outputting the double to the console (which would call ToString() on it).
Try this:
string forDisplay = string.Format("{0:0.0,00}", d);
Console.WriteLine(forDisplay);
Or, even shorter:
Console.WriteLine(string.Format("{0:0.0,00}", d));
Update:
In order to format the string according to your culture, you will need to use the Format overload that takes an IFormatProvider (i.e. a culture) and ensure that the format string uses the right characters for the different parts (, for standard thousands separator and . for standard decimal separator - see here for the meanings of each such character in a format string):
var res = String.Format(CultureInfo.CurrentCulture, "{0:0,0.00}", d);
Console.WriteLine(forDisplay);
Result:
4.434,00
You meant to do:
string formatted = String.Format("{0:0.0,00}", d);
Console.WriteLine(formatted);
string.Format returns a string -- it cannot affect the formatting of a double, since doubles have no formatting at all. Doubles only store the raw numeric value (as bits, internally).
You have the . and , around the wrong way, if I'm understanding what you're trying to do.
If you read the Custom Numeric Format Strings page on MSDN, you can see that you need to use , for the thousands separator, and . for the decimal separator, and (the important part) the target culture is irrelevant here. The format is always the same, regardless of the current culture.
So what you want to use is:
Console.WriteLine("{0:0,0.00}", d);
Then the output is:
4434 Type of: System.Double
4.434,00

Format decimal for percentage values?

What I want is something like this:
String.Format("Value: {0:%%}.", 0.8526)
Where %% is that format provider or whatever I am looking for.
Should result: Value: %85.26..
I basically need it for wpf binding, but first let's solve the general formatting issue:
<TextBlock Text="{Binding Percent, StringFormat=%%}" />
Use the P format string. This will vary by culture:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.
For example, to get a decimal value with a trailing "%" and no space between the value and the "%":
myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });
More complete example:
using System.Globalization;
...
decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)
Set your culture and "P" string format.
CultureInfo ci = new CultureInfo("en-us");
double floating = 72.948615;
Console.WriteLine("P02: {0}", (floating/100).ToString("P02", ci));
Console.WriteLine("P01: {0}", (floating/100).ToString("P01", ci));
Console.WriteLine("P: {0}", (floating/100).ToString("P", ci));
Console.WriteLine("P0: {0}", (floating/100).ToString("P0", ci));
Console.WriteLine("P1: {0}", (floating/100).ToString("P1", ci));
Console.WriteLine("P3: {0}", (floating/100).ToString("P3", ci));
Output:
"P02: 72.95%"
"P01: 72.9%"
"P: 72.95%"
"P0: 72%"
"P1: 72.9%"
"P3: 72.949%"
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
There's a simple and culture-independent approach: just use the "%" custom specifier and manually control the sign position.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierPct
A percent sign (%) in a format string causes a number to be multiplied by 100 before it is formatted. The localized percent symbol is inserted in the number at the location where the % appears in the format string.
string.Format("{0:0.0%}", 0.6493072393590115)
// outputs 64.9%
string.Format("{0:%000}", 0.6493072393590115)
// outputs %065
I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)

Categories