trant said:
I have a program which parses float values from a file. European users are
getting an error because their floats use commas instead of dots.
How can I make this universal, so whether it is a dot or comma my program
will not crash?
It's easy to keep your program from crashing. Just check for the error
instead of letting it take your program down.
As far as handling the format goes, that really depends on how lenient
you want to be. One approach would be to always replace commas with
periods before trying to parse the data. But that obviously assumes the
input string will _always_ use _either_ commas or periods for decimal
separators, and will have _no_ other separators (e.g. thousands).
An alternative approach would be to allow the user to specify the
culture for the file by name, so that you can use the appropriate
culture during parsing (using a parse overload that allows you to pass
the culture in).
Yet another alternative would be to just ask the user "commas or
periods" and choose your parsing based on that (this may require using
TryParseExact() so you can supply an exact format...that may or may not
work well with the data as it's formatted in the file, but is certainly
worth a try).
Of course, you don't say what the source of the file is. But if it's
emitted only by your own code, you could simply always write the file
using the InvariantCulture culture, or you could write the name of the
culture into the file somewhere so that you know what culture to use
when parsing it (the former being preferable for files intended only for
machine consuption, the latter probably being preferable if you expect
humans to be reading the file).
Also, if I wrote floats back to the file, how do I handle it universally?
That depends entirely on what other consumers of the file you expect
there to be and how much control you have over the file format.
I am really hoping there is some easy way to do this and dont have to have
if then code branches...
You certainly should be able to do it without an effusion of if/then
statements.
Unfortunately, without more specifics about the source of the data and
how you want it to be used, I can't offer much more than the above.
Pete