简体   繁体   English

将字符串 decimal 转换为 int

[英]Convert string decimal to int

I have a string "246246.246" that I'd like to pass to the IConvertable interface, ToInt16, ToInt32, ToIn64.我有一个字符串“246246.246”,我想将其传递给 IConvertable 接口,ToInt16、ToInt32、ToIn64。 What is the best way to parse a string with decimal places to an integer?将带小数位的字符串解析为 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 . 如果你需要舍入,你可以用Math.Floor替换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. 如果你不得不担心本地化/全球化,那么@xls说你应该在转换中应用CultureInfo。

Edit 2: Alternative method using a string function (not terribly elegant IMO - maybe it could be elegantized with a predicate function): 编辑2:使用字符串函数的替代方法(不是非常优雅的IMO - 也许它可以通过谓词函数进行优化):

Convert.ToInt64(value.Substring(0, value.IndexOf('.') > 0 ? value.IndexOf('.') : value.Length));

You should not have to Round the value as ToInt64(double) returns the rounded version already 您不应该舍入值,因为ToInt64(double)已经返回舍入版本

        string value = "246246.246";
        Convert.ToInt64(Convert.ToDouble(value));

如果你真的担心准确性而不是速度,那么十进制类型会更好。

(long)Math.Round(decimal.Parse(value));

Assuming this string comes from user input, you probably want to catch number styling. 假设此字符串来自用户输入,您可能希望捕获数字样式。 Run it through a reusable function like so... 通过像这样的可重用函数运行它...

int? ConvertToNumber(string value)
{
   if (value == string.Empty) return null;

   try
   {
       var dec = decimal.Parse(value,
           NumberStyles.AllowDecimalPoint |
           NumberStyles.Number |
           NumberStyles.AllowThousands);

       return (int)Math.Round(dec);
   }
   catch (Exception ex)
   {
       Console.WriteLine("Please input a number.");
       return null;
   }
}

The code below is to convert decimal Amount to Kobo value, which is needed when integrating to a payment gateway needing the amount in kobo's or cent.下面的代码是将十进制金额转换为 Kobo 值,在集成到需要 kobo 或美分金额的支付网关时需要这样做。

public static void Main(string[] args)
{          
  decimal amount = 50.567890m; 
        
  int koboValue = 0;
        
  String[] values =  amount.ToString("0.##").Split('.');
        
  int wholeNumber = Convert.ToInt32(values[0]);
        
  if(values.Count() > 1){
        koboValue = Convert.ToInt32(string.Join(string.Empty,values));
  }else{
        koboValue = wholeNumber * 100;
  }
        
  Console.WriteLine(koboValue);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM