【问题标题】:C#__ adding string into string using length [duplicate]C#__使用长度将字符串添加到字符串中[重复]
【发布时间】:2020-11-15 21:35:16
【问题描述】:

在我的程序中,我尝试为长度大于 3 的数字添加逗号。例如,如果数字是 1000,它应该输出 1,000。 但是,在将逗号放入第一个数字后,我不知道如何添加剩余数字。下面的代码是我得到的:

// if the answer is more than 999
string answerThousand = Convert.ToString(lbl_NumResult.Text);

if (answerThousand.Length > 3) 
{
    lbl_NumResult.Text = answerThousand[1] + "," + answerThousand[ /* What must be here to add remaining numbers? */];
}

【问题讨论】:

  • 为什么是answerThousand[1],而不是answerThousand[0]?字符串具有从零开始的索引
  • 我想把逗号放在第一个数字之后。
  • 您可以将string.FormatN 或字符串插值一起使用,例如lbl_NumResult.Text = $"{answerThousand:N}";N0
  • 对不起,我完全忘记了 0 是起始值,而不是 1。

标签: c# arrays if-statement string-length


【解决方案1】:

您可以将格式化程序传递给 ToString 方法:

decimal inputValue = 0;
if (decimal.TryParse(lbl_NumResult.Text, out inputValue))
{
    string answerThousand = inputValue.ToString("N", CultureInfo.InvariantCulture);
}

https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#NFormatString

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 2015-12-10
    • 2017-08-19
    • 2012-12-15
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多