Best way to display decimal without trailing zeroes

前端 未结 14 1428
终归单人心
终归单人心 2020-11-27 04:49

Is there a display formatter that will output decimals as these string representations in c# without doing any rounding?

// decimal -> string

20 -> 20         


        
14条回答
  •  抹茶落季
    2020-11-27 05:03

    This is yet another variation of what I saw above. In my case I need to preserve all significant digits to the right of the decimal point, meaning drop all zeros after the most significant digit. Just thought it would be nice to share. I cannot vouch for the efficiency of this though, but when try to achieve aesthetics, you are already pretty much damned to inefficiencies.

    public static string ToTrimmedString(this decimal target)
    {
        string strValue = target.ToString(); //Get the stock string
    
        //If there is a decimal point present
        if (strValue.Contains("."))
        {
            //Remove all trailing zeros
            strValue = strValue.TrimEnd('0');
    
            //If all we are left with is a decimal point
            if (strValue.EndsWith(".")) //then remove it
                strValue = strValue.TrimEnd('.');
        }
    
        return strValue;
    }
    

    That's all, just wanted to throw in my two cents.

提交回复
热议问题