Dealing with "." or "," in decimal string expression

  • Thread starter Thread starter Cybertof
  • Start date Start date
C

Cybertof

Hello,

I would like to return the good single value from a string value
in these cases :

Convert.ToSingle("23,30");
Convert.ToSingle("23.30"); // Conversion Error !!!

The result should be a single 23,30 (Single Type)

How to deal with this "." or "," for the decimal point ?
How to bypass this error and make it work ?


Regards,
Cybertof.
 
You probably have to change it by hand

int i = testString.IndexOf(".");
if(i != -1)
{
string[] splitString = testString.Split('.');
if(splitString.Length > 2)
// ERROR
if(splitString.Length < 2)
{
if(i = 0) // ".xx"
testString = "0," + splitString[0];
else // "xx."
testString = splitString[0];
}
else
testString = splitString[0] + "," + splitString[1];
}
 
Cybertof said:
I would like to return the good single value from a string value
in these cases :

Convert.ToSingle("23,30");
Convert.ToSingle("23.30"); // Conversion Error !!!

The result should be a single 23,30 (Single Type)

How to deal with this "." or "," for the decimal point ?
How to bypass this error and make it work ?

Well, you have to be aware that different countries and different
language conventions interpret 23,30 differently, for instance in Germay
decimls are separated with a comma so the above is interpreted as the
floating point number with the whole number part being 23 and the
fractional part being 30. However in Great Britain or the USA the
decimals are separated with a dot so there 23.30 is the same what people
in Germany write as 23,30.
..NET provides the Culture class to encapsulate such conventions and you
can pass such a culture to the Convert.ToSingle, here is an example
program that reads in strings from the command line and shows the result
of converting them under different cultural conventions:

using System;
using System.Globalization;

public class Test20031110 {
public static void Main (string[] args) {
string[] cultureNames = {
"en-US",
"en-GB",
"de-DE",
"de-CH"
};
CultureInfo[] cultureInfos = new CultureInfo[cultureNames.Length];
for (int i = 0; i < cultureNames.Length; i++) {
cultureInfos = CultureInfo.CreateSpecificCulture(cultureNames);
}
for (int i = 0; i < args.Length; i++) {
Console.WriteLine("Converting string {0}; output culture is {1}",
args, CultureInfo.CurrentCulture);
for (int j = 0; j < cultureInfos.Length; j++) {
try {
Console.Write("Converting with culture {0}: ", cultureInfos[j]);
float s = Convert.ToSingle(args, cultureInfos[j]);
Console.Write("converted to {0}.", s);
}
catch (Exception e) {
Console.Write("error occured: " + e);
}
finally {
Console.WriteLine();
}
}
Console.WriteLine();
}
}
}

So you need to decide from which culture your input stems and then
convert it with the intended cultural conventions
 
Back
Top