Convert string decimal to int

后端 未结 4 2010
-上瘾入骨i
-上瘾入骨i 2020-12-09 15:30

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

4条回答
  •  星月不相逢
    2020-12-09 15:57

    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));
    

提交回复
热议问题