将字符串十进制转换为int [英] Convert string decimal to int

查看:169
本文介绍了将字符串十进制转换为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));

这篇关于将字符串十进制转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆