Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal. Parse string, postfixed by a minus sign

Tags:

c#

decimal decimalVal;
Decimal.TryParse("123-", out decimalVal);
Console.WriteLine(decimalVal); // -123

Why do "123-" string parsed this way?

like image 613
rpeshkov Avatar asked Jun 17 '13 12:06

rpeshkov


People also ask

How to Parse to decimal in c#?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.

What is the purpose of the decimal parse method?

Converts the string representation of a number to its Decimal equivalent.


2 Answers

The Decimal.TryParse Method parses the input with NumberStyles.Number by default. NumberStyles.Number includes NumberStyles.AllowTrailingSign.

Decimal.TryParse Method (String, Decimal)

[...]
Parameter s is interpreted using the NumberStyles.Number style.
[...]

Number   Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style.

AllowTrailingSign   Indicates that the numeric string can have a trailing sign. Valid trailing sign characters are determined by the NumberFormatInfo.PositiveSign and NumberFormatInfo.NegativeSign properties.

like image 191
dtb Avatar answered Sep 22 '22 02:09

dtb


NumberStyles.Number enumerator is used by default:

Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style

http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx

like image 36
Filip Avatar answered Sep 22 '22 02:09

Filip