Converting string to decimal: how to handle the decimal separator in different cultures
Asked Answered
C

2

5

I need to write decimal value to ms access database, but i have a problem with conversion values to decimal in different cultures. Have a values from file, which separates by commma. I try:

public decimal CSingleCulture (string str)
{
    string sep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    string s = str.Replace(",", sep);

    return decimal.Parse(s);            
}

if NumberDecimalSeparator = "." then work is good, but if NumberDecimalSeparator = "," problems begin... decimal.Parse(s) always return vlaues separates by dot. In this situation, when inserted into a database error occurs.

Croce answered 1/12, 2013 at 8:7 Comment(0)
H
9

The recommended way to deal with this is to store the value as a number rather than a string. Both in the database and in your program. When you do that, your current problem simply never arises.

The only time you deal with numbers in string format is when you display them, or accept user input. In those scenarios you can use the user's culture settings to let them see and use their preferred separator.

Should you ever need to convert between string and number for persistence then you must use culture invariant conversion. This appears to be where you are falling down. I suspect that the file you read has no well-defined format. Make sure that when you read and write the file you use CultureInfo.InvariantCulture. If the file does have a well-defined format that differs from the invariant culture, then use an appropriate specific CultureInfo.

Helminthology answered 1/12, 2013 at 8:13 Comment(0)
S
0

Can't actually understand what is it you're trying to accomplish, and I have to agree with the other answer. But one other thing that's good to know is you can use invariant culture like so:

double.Parse("15.0", CultureInfo.InvariantCulture)

This will always expect dot character to delimit your decimal digits regardless of what is set in current thread's culture.

Sadesadella answered 1/12, 2013 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.