简体   繁体   中英

C# remove all leading and trailing zeros from decimal string

I have a decimal like like "-00.20300"

I want output like this

"-.203"

Any easy way to achieve this without removing the negative sign remove 0s and then reattaching negative sign?

Assuming you know the number of decimal digits you want in your output:

decimal val = -00.20300M;
string result = val.ToString(".###", System.Globalization.CultureInfo.InvariantCulture);
// result is "-.203"

If you don't know the number of decimal spots, you can use this method to calculate it (and include the TrimEnd because you're ignoring trailing zeros), then make the format from the count.

decimal val = -00.20300M;
var decimalCount = val.ToString(System.Globalization.CultureInfo.InvariantCulture)
    .TrimEnd('0')
    .SkipWhile(c => c != '.')
    .Skip(1)
    .Count();

var format = "." + new string('#', decimalCount);
string result = val.ToString(format, System.Globalization.CultureInfo.InvariantCulture);
// result is "-.203"

Nyssa's comment is on the right track, and would be the right way to do things, but unfortunately none of the string formats built in to C# provide the behavior that you want.

Gunr's answer is correct, but only works when you know the number of useful digits.

Here is a general solution:

public static string TrimmedStringConversion(string numberString)
{
    const string minusSign = "-";
    var returnString = string.Empty;
    if (numberString.StartsWith(minusSign))
    {
        returnString = minusSign;
        numberString = numberString.Remove(0,1);
    }

    returnString += numberString.Trim('0');
    return returnString;
}

And the unit test/usage:

[TestMethod]
public void TestStringConversion()
{
    var startingString = "-00.20300";
    var convertedString = TrimmedStringConversion(startingString);
    Assert.AreEqual("-.203", convertedString);
}

you have to format the decimal value

decimal decValue = -00.20300M;
string result = decValue.ToString(".###");

Console.WriteLine(result);

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