简体   繁体   中英

Format a long string into a short string C#

I have some strings such as:

1.5555555555555
2.3421354325435354545
4.509019292

I want to format them into a string such as:

1.5555
2.3421
4.5090

I tried to use the C# String.Format but I can not get it to correctly work.

Can someone please give me the correct c# statement to accomplish this?

Thanks.

string.Format("{0:N4}",decimalValue);

Standard Numeric Format Strings

Custom Numeric Format Strings

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".

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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