n00b
n00b

Reputation: 911

How to format decimal to truncate all zeros in decimal places except the first two?

I'd like to achieve the following results for input in C#. How to do that?

10.000000 -> 10.00
10.200000 -> 10.20
10.254550 -> 10.25455

Thanks in advance.

Upvotes: 2

Views: 125

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

value.ToString("0.00####################");

Prints exactly what you need for all your sample inputs.

Both 0 and # are part of custom numeric format pattern. You can read what they mean on msdn: Custom Numeric Format Strings.

Upvotes: 5

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try this

string s = "10.254550";
        Response.Write(Convert.ToDecimal(s).ToString("#.00##"));

# will consider only digits except zero

Upvotes: 2

Related Questions