将字符串十进制转换为int
我有一个字符串"246246.246",我想传递给IConvertable接口ToInt16,ToInt32,ToIn64.将带小数位的字符串解析为整数的最佳方法是什么?
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)));
如果需要四舍五入,可以将Math.Floor
替换为Math.Round
.
If you need to round you could replace Math.Floor
with Math.Round
.
编辑:由于您在评论中提到要四舍五入:
Since you mentioned in a comment that you'll be rounding:
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));
如果您不得不担心本地化/全球化的问题,那么正如@xls所说,您应该在转换中应用CultureInfo.
If you have to worry about localization/globalization then as @xls said you should apply a CultureInfo in the conversions.
使用字符串函数的替代方法(不是很优雅的IMO-也许可以通过谓词函数来实现优雅的装饰):
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));