简体   繁体   English

为什么将包含浮点数的字符串解析为小数?

[英]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. 因为3.14会被当作double精度字面量,除非您另外指定。 And there is no implicit conversion from double to decimal . 并且没有从doubledecimal隐式转换。

You can use m suffix to make it a decimal literal: 您可以使用m后缀使其为十进制文字:

decimal element = 3.14m;

You can refer to C# Language Specification §2.4.4.2 Integer Literals for more info about literal suffixes. 您可以参考C#语言规范 §2.4.4.2整数文字以获取有关文字后缀的更多信息。

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. 请注意,在第一个代码中,您并没有直接将string分配给decimaldecimaldecimal.Parse返回decimal因此那里没有转换问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将两个整数(一个包含整数部分,另一个包含小数部分)组合成一个浮点数 - Combine two integers (one containing the integer part, the other the decimal part) into a floating point number 浮点数解析:是否有 Catch All 算法? - Floating Point Number parsing: Is there a Catch All algorithm? 如何使用String.Format格式化带有逗号分隔符和浮点小数的数字? - How to use String.Format to format a number with comma separators and floating decimal point? 如何格式化数字而不保留小数部分但保留浮点数? - How to format number without decimal part but preserving floating point? 为什么int和decimal抛出DivideByZeroException而浮点数却没有? - Why do int and decimal throw DivideByZeroException but floating point doesn't? C#将包含浮点的字符串转换为整数 - C# Converting a string containing a floating point to an integer 用逗号和浮点数转换十进制 - Convert decimal with comma and floating point 为什么解析具有浮点值的字符串会给我带点后位数的数字 - Why parsing of a string with float value gives me number with big number of digits after point 如何将包含指数数字的字符串转换为十进制并返回到字符串 - How to convert a string containing an exponential number to decimal and back to string 将数字转换为字符串,无需任何格式,并使用“。”作为浮点分隔符 - Convert number to string without any formating and using “.” as floating point separator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM