Search code examples
c#bindingformatdecimalzero

Adding zero numbers to my decimal value


I don't know why but I've been struggling for something very simple this day.

I'm working with decimal values assigned to the Text property of a Label which is inside a repeater at the same time.

In my repeater ItemDataBound I'm doing this:

//myValue eventually could be just an integer but I want it in decimal format.
lblTotal.Text = string.Format("{0:0.000}", myValue);

I tried this before:

lblTotal.Text = string.Format("{0:#.###}", myValue);

Nothing works!!! I want to show values from database that are in that format but when refresh the table with a postback for any operation, my values become just "0" but it must be "0.000". If it's "5.300" it changes to "5.3"

What am I doing wrong?

I don't what to include the format in the HTML. Just in the code behind at the moment of the repeater binding.


Solution

  • You can use the .ToString() with a custom specifier. In the code below lblTotal.Text will be set to "5.300".

    var myValue = 5.3;
    lblTotal.Text = myValue.ToString("0.000");