简体   繁体   中英

Why is Parsing a String containing a floating point number to Decimal Allowed?

Why is :

string arr = "3.14";
decimal element = decimal.Parse(arr);

Allowed

But:

decimal element = 3.14;

Not allowed

Because 3.14 is treated as a double literal unless you specify otherwise. And there is no implicit conversion from double to decimal .

You can use m suffix to make it a decimal literal:

decimal element = 3.14m;

You can refer to C# Language Specification §2.4.4.2 Integer Literals for more info about literal suffixes.

Note that in the first code you are not directly assigning a string to a decimal , decimal.Parse returns decimal so there is no conversion issue there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM