Question

I have 2 different fields saved in a database as money : Balance & Amount. However when I try to display these on an mvc view, the Balance is already rounded to 2DP whilst the amount is being displayed as 4dp.

 @foreach (var trans in ViewBag.Transactions)
{
    <tr>
        <td>
            @trans.Date
        </td>
        <td>
            @trans.Details
        </td>
        <td>
            @trans.Currency
        </td>
        @if (trans.AccountTo == ViewBag.SelectedAccount)
        {
            <td>
               + @trans.Amount
            </td>
            <td>

            </td>
            <td>
                @trans.AccountFrom
            </td>

I have already tried @trans.Amount.ToString("#.##") or creating a helper similar to this: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx but still did not work. How can I round it to 2dp?

Was it helpful?

Solution

When performing a custom string formatting, there is a distinct difference between using # and 0 as the place holder.

With the original decimal being 4 decimal places, using either of the two place holders, 0 or #, will work when only wanting 2 decimal places:

// numeric real literal to be treated as decimal with m or M suffix
decimal d = 100.1255M; 

string s1 = d.ToString( "#.##" ); // 100.13
string s2 = d.ToString( "0.00" ); // 100.13

However, if you wanted 5 decimal places, then this is where the difference becomes apparent:

decimal d = 100.1255m;

string s1 = d.ToString( "#.##" ); // 100.13
string s2 = d.ToString( "0.00" ); // 100.13
string s3 = d.ToString( "#.#####" ); // 100.1255
string s4 = d.ToString( "0.00000" ); // 100.12550

Reviewing MSDN on Custom Numeric Format Strings will help shed some light on the differences:

Zero Placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

For more detailed information: The "0" Custom Specifier.

Digit placeholder
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.

For more detailed information: The "#" Custom Specifier

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top