Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string to decimal with trailing zero(s)

Tags:

c#

Suppose that we have stringvalue=125.32600 when it convert to decimal value with this code

decimal d;
decimal.tryparse(stringvalue,out d)

d value is 125.326 how can I do this convert with final result 125.32600

like image 733
Omital Avatar asked Dec 12 '22 10:12

Omital


1 Answers

You cannot because 125.32600 is equal to 125.326. In this case however I guess that you want to print it out with specific format, which can be done like this:

Console.WriteLine(d.ToString("f5"));

Read Standard Numeric Format Strings

UPDATE

Extension method:

public string Format(this decimal source, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
    }

    return source.ToString("f" + precision);
}

which can be used like this:

Console.WriteLine(d.Format(5));
like image 184
Zbigniew Avatar answered Dec 30 '22 08:12

Zbigniew