简体   繁体   English

将长字符串格式化为短字符串C#

[英]Format a long string into a short string C#

I have some strings such as: 我有一些字符串,如:

1.5555555555555 1.5555555555555
2.3421354325435354545 2.3421354325435354545
4.509019292 4.509019292

I want to format them into a string such as: 我想将它们格式化为一个字符串,例如:

1.5555 1.5555
2.3421 2.3421
4.5090 4.5090

I tried to use the C# String.Format but I can not get it to correctly work. 我试图使用C#String.Format,但我不能让它正确工作。

Can someone please give me the correct c# statement to accomplish this? 有人可以给我正确的c#声明来完成这个吗?

Thanks. 谢谢。

It's unclear if you'll always be dealing with numeric values. 目前还不清楚你是否总是在处理数值。 If you want to avoid parsing the strings as numbers, you might try something like this: 如果您想避免将字符串解析为数字,可以尝试这样的方法:

public static string TrimTo(string str, int maxLength)
{
    if (str.Length <= maxLength)
    {
        return str;
    }
    return str.Substring(0, maxLength);
}

This will trim the provided string to six characters, if it's longer than six. 这会将提供的字符串修剪为六个字符(如果长度超过六个字符)。 This seems to be what you want, but (as Kees points out), will do something unexpected with a string like "1234567.890". 似乎是你想要的,但(正如Kees指出的那样),会用“1234567.890”这样的字符串做一些意想不到的事情。

The conditional clause is necessary here because String.Substring will complain if the second index is outside of the string (if the string is shorter than maxLength , in other words). 这里条件子句是必需的,因为如果第二个索引在字符串之外, String.Substring会抱怨(如果字符串比maxLength短,换句话说)。

(If you've played around with C# 3.0 extension methods at all, you might recognize this, slightly modified from the above, as an excellent opportunity for one: string trimmed = s.TrimTo(10); ) (如果您已经使用过C#3.0 扩展方法 ,您可能会认识到这一点,从上面稍作修改,作为一个绝佳的机会: string trimmed = s.TrimTo(10);

如果将字符串转换为双精度数,则可以使用String.Format指定在将其重新格式化为字符串时要包含的小数位数。

String.Format("{0:0.0000}", double.Parse("1.55555555555555"))

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

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