How can I strip zeros and decimal points off of decimal strings?

陌路散爱 提交于 2019-12-04 11:02:09

You can also use decimal's ToString with a parameter:

string s = dec.ToString("0.#");

Note: You may have an internationalization issue with your code. The way you have coded it, it will use the culture info from the user's computer, which may have something other than . for the decimal separator. This might cause your program to give incorrect results for users that have . for thousands separator.

If you want to guarantee that the parse method will always behave the same, you could use CultureInfo.InvariantCulture. If you do actually want to parse the string according to the user's culture settings, what you are doing is fine.

Use:

 Console.WriteLine("{0:0.####}", dec);

Learn more about numeric format strings from here...

This string format should make your day: "0.#############################". Keep in mind that decimals can have at most 29 significant digits though.

Examples:

? (1000000.00000000000050000000000m).ToString("0.#############################")
-> 1000000.0000000000005

? (1000000.00000000000050000000001m).ToString("0.#############################")
-> 1000000.0000000000005

? (1000000.0000000000005000000001m).ToString("0.#############################")
-> 1000000.0000000000005000000001

? (9223372036854775807.0000000001m).ToString("0.#############################")
-> 9223372036854775807

? (9223372036854775807.000000001m).ToString("0.#############################")
-> 9223372036854775807.000000001
unknown
public static string RemoveDecimalsFromString(string input)
{
    decimal IndexOfDot = input.IndexOf(".");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < IndexOfDot; i++)
    {
        sb.Append(input[i]);
    }

    return sb.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!