Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal.TryParse doesn't parse my decimal value

Tags:

When I tried to convert something like 0.1 (from user in textbox), My value b is always false.

bool b = Decimal.TryParse("0.1", out value); 

How can it be here to work?

like image 765
cadi2108 Avatar asked Jul 03 '12 13:07

cadi2108


People also ask

How to use Decimal TryParse in c#?

TryParse(value, style, culture, number) Then Console. WriteLine("Converted '{0}' to {1}.", value, number) Else Console. WriteLine("Unable to convert '{0}'.", value) End If ' Displays: ' Converted '1345,978' to 1345.978. value = "1.345,978" style = NumberStyles.

What is the purpose of the Decimal parse method?

Converts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format. Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information.

What is C# Decimal?

In C#, Decimal Struct class is used to represent a decimal floating-point number. The range of decimal numbers is +79,228,162,514,264,337,593,543,950,335 to -79,228,162,514,264,337,593,543,950,335.


2 Answers

Specify the culture for the parsing. Your current culture uses some different number format, probably 0,1.

This will successfully parse the string:

bool b = Decimal.TryParse("0.1", NumberStyles.Any, CultureInfo.InvariantCulture, out value); 
like image 158
Guffa Avatar answered Sep 18 '22 19:09

Guffa


Too late to the party, but I was going to suggest forcing the culuture to en-US but Invariant is a better sln

decimal value; bool b = Decimal.TryParse("0.1", NumberStyles.Any, new CultureInfo("en-US"), out value); 
like image 45
Matt Roberts Avatar answered Sep 19 '22 19:09

Matt Roberts