Convert strings to decimal: how to handle decimal separator in different cultures

I need to write a decimal value to ms access database, but I have a problem with conversion values ​​to decimal in different cultures. Have values ​​from the file that commma shares. I'm trying to:

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 the work is good, but if NumberDecimalSeparator = "," problems begin ... decimal.Parse(s) always return the vlaues delimited by a dot. In this situation, when inserting into a database error occurs.

+6
source share
2 answers

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

The only time you deal with numbers in a string format is when you display them or accept user input. In these scenarios, you can use custom culture settings so that they can see them and use their preferred separator.

If you need to convert a string and a number to save, you must use the culture invariant conversion. This seems to be where you fall. I suspect that the file you are reading does not have a clearly defined format. Make sure you use CultureInfo.InvariantCulture when reading and writing the file. If the file has a well-defined format that differs from the invariant culture, then use the corresponding specific CultureInfo file.

+9
source

I can’t understand what you are trying to accomplish, and I have to agree with another answer. But one more useful thing - you can use such an invariant culture:

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

It will always be expected that the dot character will divide your decimal digits no matter what is set in the current thread culture.

0
source

Source: https://habr.com/ru/post/959110/


All Articles