I´m trying to parse a LinearGradientBrush from Xaml strings, without any problem I use the ColorConverter.ConvertFromString for normal text or html color conversion.
Recently I came across some colors parsed from Adobe Illustrator into Expression Blend using the ScRGB formatting "sc#scA, scR, scG, scB". That seems to break the ColorConverter, as the ScA value from the Color struct seems to parse the value wrong; for example 0.2 becomes 2 and 0.5 becomes 5.
My code is fairly straightforward:
string colorStr = "sc#0.117647059, 0, 0, 0";
Color color = (Color)ColorConverter.ConvertFromString(colorStr);
Console.WriteLine(color.ScA);
Output: 1,176471E+08, Expected: 0,1176471
Is this a bug in the .NET Framework (I'm on 4)? Is there a workaround? Does anyone have a clean-fix?
You have a culture problem. Clearly you are living in a part of the world where the decimal point in a floating point value is a comma instead of a period. But your color string is formatted with a period. So when the value is converted to float, it sees the period in the string as a thousands separator, not a decimal point. And "0117647059" is indeed 1,176471e8.
You'll need to use the ColorConverter.ConvertFrom() overload, it accepts a CultureInfo reference. Pass CultureInfo.InvariantCulture. Or whack the Adobe tooling over the head somehow so it generates properly localized strings.
Related
I am new to C # and I am currently having problems with the following. In C #, I have a Pi floating point number and I want to convert it to a string using the ToString() method. But the conversion gives a string result with a comma "3,1415". On another machine, the same gives the string result with the dot "3.1415". What is the reason for this and what should I do to get a dotted string result?
EDIT: The problem is, I can't change the code, but I can install and uninstall .Net frameworks, change my OS settings, etc.
Edit: if you can't change the code. Change the language/localization of the system to one which uses dot as decimal separator. In Control Panel or Settings.
You should look at internationalization and localization in the System.Globalization namespace.
The advice here is to use one CultureInfo specific for parsing numbers or writing numbers to string.
var flt = 232.23f;
var str = flt.ToString(CultureInfo.InvariantCulture); //for example, you can use CultureInfo.CurrentCulture
This allows you to keep the ThreadCulture without change it.
But take a look at this link https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=net-5.0 .Take your time, is dense.
I would just set the current culture at the entry point of your program.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
However I would also check the regional settings and so forth on the machine where the comma separator appears.
It is related with current culture info. You can specify the culture info in ToString method as a parameter like;
var convertedFloat = floatVariable.ToString(new CultureInfo("en-GB"));
Thanks to GSerg, for comment about Windows regional settings. That solves my problem. In the Windows Control panel enter Region and Language. In the Formats tab click Additional Settings and in the Decimal symbol field specify what decimal separator must be used when converting a floating point number to a string.
Whats the best way to make the conversion work when you have:
string a = "10.0123";
string b = "10,0123";
And the cultureinfo is either swedish or english, it needs to work with both.
I tried:
double aSwe = Convert.ToDouble(a, CultureInfo.GetCultureInfo("sv-SE"));
double bSwe = Convert.ToDouble(b, CultureInfo.GetCultureInfo("sv-SE"));
double aInv = Convert.ToDouble(a, CultureInfo.InvariantCulture);
double bInv = Convert.ToDouble(b, CultureInfo.InvariantCulture);
Since '.' is not a valid separator in Swe and ',' is not valid in Eng I dont know how to make it work with both using the same code.
Only solution I come up with is to replace the comma or dot before converting but it feels like there should be better solution?
You shouldn't try to make it work with both without any extra context.
It's like trying to parse "06/05/2010" as a date without any cultural information: it could mean the May 6th or June 5th.
Likewise "1,234" is either a value a bit more than a thousand, or a bit more than one: you need to know the cultural information in order to interpret it unambiguously.
So instead of trying to solve the problem of interpreting something without enough information, I suggest you focus on the problem of getting all the information you need (or changing the way you get your text data to always be in one particular format).
I'm currently doing an app, that needs to be able to work with the US number layout (123,456.78) as well as with the German layout (123.456,78).
Now my approach is to use NumberFormatInfo.InvariantInfo about like this:
temp = temp.ToString(NumberFormatInfo.InvariantInfo);
this works great when for example reading a number from a textbox. When System is set to English format it will take the . as separator, when it's set to German it will use the ,.
So far so good....but here's the problem: I have a device that returns info in the American format, and that won't change (transmitted via RS232). So I receive something like 10.543355E-00.
Now when on German setting the . will be discarded since it's just the group separator
and the number I will end up with is 10543355....which is a lot more :)
I tried with the same technique thinking this would make the whole thing kind of 'cultureless' to be able to process it independently from the system language but it didn't work :)
I hope you can maybe help me here...I'd love to use a way without having to implement the whole culture stuff etc since all I need here is really numbers that get calculated the right way.
You should use CultureInfo.InvariantCulture when parsing strings from the device. This will cause it to use the invariant culture, which has the US rules for decimal separation.
Edit in response to comments:
The issue is not when you call .ToString(), but rather when you read the string from the device, and convert it to a number:
string inputFromRS232Device = GetDeviceInput();
double value;
// You need this when converting to the double - not when calling ToString()
bool success = double.TryParse(
inputFromRS232Device,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out value);
I'm trying to build a "simple" web app that calculates either a male or females body fat % based on the U.S. Navy's circumference formula. I have the majority of the app completed at this point. However, I cannot figure out why the way I've setup the formula below won't work. Two of the values are underlined in red in my .cs file.
My Formula:
TBBodyFat.Text = Convert.ToString(495 / (1.0324-.19077(Math.Log(Convert.ToDouble(TBWaist.Text)-Convert.ToDouble(TBNeck.Text)))+.15456(Math.Log(Convert.ToDouble(TBHeight.Text)))));
Original Example:
%Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450
Pop-Up for the two underlined values (.19077 and .15456):
struct System.Double
Represents a double-precision floating-point number.
Error:
Method name expected
TBBodyFat.Text = Convert.ToString(495 / (1.0324-.19077*
(Math.Log(Convert.ToDouble(TBWaist.Text)-Convert.ToDouble(TBNeck.Text)))+.15456*
(Math.Log(Convert.ToDouble(TBHeight.Text)))));
C# (not any programming language I've yet encountered) does not take adjacency of numbers to mean multiplication!
Well you need to use "*" for multiplication. Plus I'm not sure whether C# allows ".123" style numeric literals without leading 0.
Try:
TBBodyFat.Text =
Convert.ToString(495/
(1.0324-0.19077*(Math.Log(Convert.ToDouble(TBWaist.Text)-Convert.ToDouble(TBNeck.Text)))+0.15456*(Math.Log(Convert.ToDouble(TBHeight.Text)))));
Put * while multiplying like .8*(b-200) .If you will put directly .8(b-200) it will show error that method name expected.
I noticed my doubles contain different precision characters depending on regional settings.
For example:
3,47 or 3.45
How can I enforce the double should always contain a . precision character?
Problem is once I serialize the class containing this double to XML, it gets shipped to other systems expecting a standard result.
So after reading your responses (and thanks), do you guys recommend changing the property to a string, (making the replacements in a string), so that it serializes with the string value (not the double)?
You need to put the double to string using the Invariant Culture.
double d = 3.47;
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
You will need to format with the InvariantCulture.
Note that the "." and "," formatting characters are interpreted according to the culture settings.
This little tutorial will be the answer you need, I expect:
http://www.java2s.com/Tutorial/CSharp/0440__I18N-Internationalization/Parsingnumberswithcultureinvariantparsing.htm
double.Parse(numberString, CultureInfo.InvariantCulture);
The double itself doesn't include a "." or a ",", only the print out of the representation does. You can read up on custom formats here.
[Update according to OP]
I don't know exactly what your design looks like, but it would probably be smart to create a string property on your DTO, which would output the formatted string of your double, and then mark your double property as not serializable.
When you need to do this for all numbers in your current applicaton, you can use the following to set it application-wide (new threads will inherit this setting):
// use this statement to force the default:
Application.CurrentCulture = CultureInfo.InvariantCulture;
string s = myNumber.ToString();
// for one number you have to remember to use:
string s = myNumber.ToString(CultureInfo.InvariantCulture);
Note: by default, your application, whether ASP.NET or WinForms, will use the culture settings of the system it is running on (in ASP.NET, you can set the culture globally in the web.config).