C#字符串转换为十进制INT [英] C# Convert String Decimal to Int
问题描述
我有一个字符串246246.246我想传递给IConvertable接口,ToInt16,ToInt32,ToIn64。什么是解析带小数位为整数的字符串的最佳方式?
这是一个解决方案,但有一个更好的解决方案?
字符串值=34690.42724;
Convert.ToInt64(Convert.ToDouble(值));
要做到这一点贴现四舍五入,你可以这样做:
Convert.ToInt64(Math.Floor(Convert.ToDouble(值)));
如果你需要你周围,你可以取代 Math.Floor $ C 。$ C>与
Math.Round
编辑:既然你在提到评论说,你会四舍五入:
Convert.ToInt64(Math.Round(Convert.ToDouble(值)));
如果您有作为@xls说你应该在应用的CultureInfo担心本地化/全球化然后。转换
编辑2:是一个字符串函数替代方法(不是非常优雅IMO - 也许它可以使用谓词功能elegantized):
Convert.ToInt64(value.Substring(0,value.IndexOf()>'。'0 value.IndexOf(? '。'):value.Length);
I have a string "246246.246" that I'd like to pass to the IConvertable interface, ToInt16, ToInt32, ToIn64. What is the best way to parse a string with decimal places to an integer?
This is a solution, but is there a better solution?
string value = "34690.42724";
Convert.ToInt64(Convert.ToDouble(value));
To do this discounting rounding you could do:
Convert.ToInt64(Math.Floor(Convert.ToDouble(value)));
If you need to round you could replace Math.Floor
with Math.Round
.
Edit: Since you mentioned in a comment that you'll be rounding:
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));
If you have to worry about localization/globalization then as @xls said you should apply a CultureInfo in the conversions.
Edit 2: Alternative method using a string function (not terribly elegant IMO - maybe it could be elegantized with a predicate function):
Convert.ToInt64(value.Substring(0, value.IndexOf('.') > 0 ? value.IndexOf('.') : value.Length);
这篇关于C#字符串转换为十进制INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!