如何将 Int/Decimal 转换为 C# 中的浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1042099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert Int/Decimal to float in C#?
提问by Jared
How does one convert from an int or a decimal to a float in C#?
如何在 C# 中将整数或十进制数转换为浮点数?
I need to use a float for a third-party control, but I don't use them in my code, and I'm not sure how to end up with a float.
我需要为第三方控件使用浮点数,但我没有在我的代码中使用它们,而且我不确定如何以浮点数结束。
采纳答案by heavyd
You can just do a cast
你可以做一个演员
int val1 = 1;
float val2 = (float)val1;
or
或者
decimal val3 = 3;
float val4 = (float)val3;
回答by nedlud
It is just:
它只是:
float f = (float)6;
回答by Chris Pietschmann
The same as an int:
与 int 相同:
float f = 6;
Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:
此外,这里还介绍了如何以编程方式从 int 转换为 float,C# 中的 single 与 float 相同:
int i = 8;
float f = Convert.ToSingle(i);
Or you can just cast an int to a float:
或者您可以将 int 转换为浮点数:
float f = (float)i;
回答by Dave the Troll
You don't even need to cast, it is implicit.
您甚至不需要强制转换,它是隐式的。
int i = 3;
float f = i;
A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
可以在此处查看隐式数字转换的完整列表/表格 http://msdn.microsoft.com/en-us/library/y5b434w4.aspx