Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to convert string to decimal i try so many combination cant get right number.
string a = "14,8";
string b = "10,36";

What I have tried:

string a = "14,8";
string b = "10,36";

decima c = MyClass.CustomDecimalParse(string value); //i got 148 and 1036 WHYYYY!!??
public static decimal CustomDecimalParse(string value)
        {
            decimal number = 0;
            return Decimal.TryParse(value, out number) ? number : 0;
        }
Posted
Updated 22-May-18 22:16pm

You need to use a culture style and formatter, as your number formats are not the default. See Decimal.TryParse Method (System) | Microsoft Docs[^].
 
Share this answer
 
Comments
CPallini 23-May-18 4:12am    
5.
Richard MacCutchan 23-May-18 4:13am    
Thanks; that was quick. :)
Member 11381811 23-May-18 4:15am    
If I set CultureInfo on Default doesnt work..
Richard MacCutchan 23-May-18 4:24am    
Then do not use default, use the correct one.
This is a globalisation thing. In one culture "1,234" is 1234 and in another it is 1.234. The computer is using whatever its current culture is so that might be in the settings somewhere, in the OS etc. If you want to use a specific culture then supply it in your TryParse method. For example if you use German (de) that recognises "14,8" as "14.8". So use your intended culture or change the general culture of the context your code runs in.

public static decimal CustomDecimalParse(string value)
{
    decimal number = 0;
    return Decimal.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("de-DE"), out number) ? number : 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900