String to Double Conversion (Comma to dot issue)

2.1k views Asked by At

Struggling with the basics - I'm trying to code a simple currency converter. The XML provided by external source uses comma as a decimal separator for exchange rate (kurs_sredni):

<pozycja>
    <nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
    <przelicznik>1</przelicznik>
    <kod_waluty>THB</kod_waluty>
    <kurs_sredni>0,1099</kurs_sredni>
</pozycja>

I already managed to load the data from XML into a nifty list of objects (kursyAktualne), and now i'm trying to do the math. I'm stuck with conversion.

First of all i'm assigning "kurs_sredni" to a string, trying to replace "," with "." and converting the hell out of it:

string kursS = kursyAktualne[iNa].kurs_sredni;
kursS.Replace(",",".");
kurs = Convert.ToDouble(kursS);
MessageBox.Show(kurs.ToString());

The messagebox show 1099 instead of expected 0.1099 and kursS still has comma, not dot.

Tried toying with some cultureInfo stuff i googled, but that was too random. I need to understand how to control this.

4

There are 4 answers

0
Filip On BEST ANSWER

It is because Replace method returns new string with replaced characters. It does not modify your original string.

So you need to reassign it:

kursS = kursS.Replace(",",".");
3
Jon Skeet On

Just use decimal.Parse but specify a CultureInfo. There's nothing "random" about it - pick an appropriate CultureInfo, and then use that. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        var french = CultureInfo.GetCultureInfo("fr-FR");
        decimal value = decimal.Parse("0,1099", french);
        Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); // 0.1099
    }
}

This is just using French as one example of a culture which uses , as a decimal separator. It would probably make sense to use the culture of the origin of the data.

Note that decimal is a better pick for currency values than double - you're trying to represent an "artificial" construct which is naturally specified in base10, rather than a "natural" continuous value such as a weight.

(I would also be wary of a data provider who provides data in a non-standard format. If they're getting that wrong, who knows what else they'll get wrong. It's not like XML doesn't have a well-specified format for numbers...)

0
Jaspreet Singh On

Replace returns a string. So you need an assignment.

kursS = kursS.Replace(",", ".");

There is "neater" way of doing this by using CulturInfo. Look this up on the MSDN website.

0
Dacker On

You replace result isn't used, but the original value that doesn't contain the replace. You should do:

kursS = kursS.Replace(",", ".")

In addition this method isn't really safe if there are thousands-separators. So if you are not using culture settings you should do:

kursS = kursS.Replace(".", "").Replace(",", ".")