1

How to display decimal with 3 zeros after comma, without trailing? My code is

<td>@decimal.Parse(item.QuantityKg.ToString()).ToString("G29")</td>
11
  • 2
    Possible duplicate of Using String Format to show decimal upto 2 places or simple integer Commented Feb 10, 2016 at 14:24
  • 2
    How about ToString("N3") instead? Commented Feb 10, 2016 at 14:24
  • What type is QuantityKg? Commented Feb 10, 2016 at 14:25
  • 1
    @JurijusAmbros Then why you generate it's string representation and parse it to decimal if it is already decimal? Why not just <td>@item.QuantityKg.ToString("N3")</td> instead? Commented Feb 10, 2016 at 14:27
  • 1
    String.Format("{0:N3}",item.QuantityKg) will work with both decimal and decimal?. As a rule, String.Format works even if a type's specific ToString() doesn't allow a formatting string Commented Feb 10, 2016 at 14:51

1 Answer 1

2

Since your QuantityKg is decimal? instead of decimal, you can use it's Value property and use "N" format specifier with 3 precision.

If everything is okey other than this, this should work in your case;

<td>@item.QuantityKg.Value.ToString("N3")</td>

But this throws InvalidOperationException if QuantityKg is null, so using string.Format would be better to catch this situation which generates empty string if it is null as Panagiotis mentioned.

<td>@string.Format("{0:N3}", item.QuantityKg)</td>
Sign up to request clarification or add additional context in comments.

2 Comments

Or use String.Format, so that a null value will result in an empty string instead of an YSOD. It also doesn't care if the value is decimal or decimal?
@PanagiotisKanavos Yeah, that's seems better. Added my answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.