【问题标题】:Convert String with a number and string to an INT value C# [duplicate]将带有数字和字符串的字符串转换为 INT 值 C# [重复]
【发布时间】:2019-09-25 14:05:59
【问题描述】:

我有一个价值,例如$40,000。我想将其转换为int。 我已经尝试过int.Parse(number)int.TryParse()Convert.ToInt32(),但不工作。

如何将$40,000 转换为40000 作为int 值?

【问题讨论】:

  • 先去掉$,,然后解析。
  • 解析为Decimal (double) 然后转换为int

标签: c#


【解决方案1】:

解析为decimal (double) 然后转换为int

  string source = "$40,000";

  Decimal money = Decimal.Parse( 
    source,                               // source should be treated as
    NumberStyles.Currency,                // currency 
    CultureInfo.GetCultureInfo("en-US")); // of the United States

  // truncation: 3.95 -> 3
  int result = (int)money; 
  // rounding: 3.95 -> 4
  // int result = (int)(money > 0 ? money + 0.50M : money - 0.50M); 

或者,如果您确定不会出现 cents(例如,"$39,999.95""$40,000.05"

  string source = "$40,000";

  int result = int.Parse( 
    source,                               // source should be treated as
    NumberStyles.Currency,                // currency 
    CultureInfo.GetCultureInfo("en-US")); // of the United States

【讨论】:

    【解决方案2】:
    string moneyAmount = "$40,000";
    moneyAmount = moneyAmount.Replace("$", "").Replace(",", "");
    
    return int.Parse(moneyAmount);
    

    【讨论】:

    • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。提供的这个答案可能是正确的,但它可以从解释中受益。仅代码答案不被视为“好”答案。来自review
    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 2013-11-04
    • 2014-07-05
    • 2013-09-01
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 2023-02-15
    相关资源
    最近更新 更多