TTCG
TTCG

Reputation: 9113

Trim zeros in the decimal

I would like to remove the extra zeros if they don't have any decimal values. But if they have, I would like to show them. enter image description here

In the picture, I want to height the unnecessary 0 from the 10.00 and 20.00. But I want to show the other 3 records below.

I used c#, asp.net 4.0 and GridView to display .

Upvotes: 3

Views: 3813

Answers (5)

Chuck Savage
Chuck Savage

Reputation: 11955

You could always go at it the programmers way.

Define a TemplateField that is a label and its Text property is bound like so: Text='<%# WeightText( Container.DataItem ) %>'.

Define the WeightText method in the code behind that takes the Container.DataItem as a parameter.

protected string WeightText(object dataItem)
{
   // cast it to your object
   MyObject myObject = (MyObject)dataItem;
   decimal d = (decimal)myObject.Weight;
   decimal fraction = d - decimal.Remainder(d);
   if(fraction > 0)
       return d.ToString(); // string with fraction (format this however you want)
   else
       return decimal.Remainder(d).ToString(); // string without fraction (format this however you want)
}

Upvotes: 0

Jakub Šturc
Jakub Šturc

Reputation: 35797

If you have trouble with formats Kathy Kam's .NET Format String 101 is ultimate resource for you.

Upvotes: 3

Bala R
Bala R

Reputation: 109027

Try

<asp:BoundField DataField="Weight" DataFormatString="{0:#.##}" />

Upvotes: 3

Joe Enos
Joe Enos

Reputation: 40431

I can't see the picture, but it sounds like you just need a format string: The # character represents a digit if it's needed, and a 0 character represents that you'll always have a digit. So a format string of "#.##" sounds like it might be what you need.

Upvotes: 2

Andy White
Andy White

Reputation: 88475

I believe the "#" custom format character might work for you. Take a look at the "Custom Numeric Format Strings" on MSDN:

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

You will need to specify the "Format" for the column somewhere in your GridView configuration.

Upvotes: 2

Related Questions