转换为浮点数的最佳/最快方法 [英] Best/quickest way to convert to float
本文介绍了转换为浮点数的最佳/最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我试图输入和输出浮点数.
So I am trying to have input and output in float number.
Console.WriteLine("Enter float number: ");
float number = Console.ReadLine();
Console.WriteLine("{0}", number);
我看到ReadLine将具有字符串格式的问题,这将导致错误CS0029:无法将类型'string'隐式转换为'float'(CS0029)".现在,如何将字符串转换为float?我可以使用float.Parase:
I see the problem that ReadLine will have format in string which will cause "Error CS0029: Cannot implicitly convert type 'string' to 'float' (CS0029)". Now, how do I convert string to float? I could use float.Parase:
string unformattedNumber;
float number;
Console.WriteLine("Enter float number: ");
unformattedNumber = Console.ReadLine();
number = float.Parse(unformattedNumber);
Console.WriteLine("{0}", number);
但是有没有更好的方法可以在与ReadLine语句相同的行中进行转换?
But is there any better way to convert in same line as ReadLine statement is at?
推荐答案
TryParse
是最好的方法.
请参阅: http://msdn.microsoft.com/zh-CN/library/system.single.tryparse.aspx
这篇关于转换为浮点数的最佳/最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文