Reputation: 354
So i've checked Format currency without rounding and some other posts, but i'm not sure i'm finding my specific error anywhere.
View
@foreach (var item in attyData)
{
<tr>
<td>@String.Format("{0:C0}", item.cashMoney)</td>
</tr>
}
<tr class="info">
<td>@String.Format("{0:C0}", Model.attyData.Sum(item => item.cashMoney))</td>
</tr>
Database Results for cashMoney
12.2
13.3
View Results
$12
$13
Total Line - $26
How do I get my individual total line to not round? Data type for cashMoney is decimal?
Upvotes: 0
Views: 490
Reputation: 11713
If you don't want it rounded, use a different Currency ("C") Format Specifier.
For example:
decimal a = 12.2M;
decimal b = 13.3M;
var sum = a + b;
Console.WriteLine($"C0 --- > {a,-8:C0} -- {b,-8:C0} -- {sum,-8:C0}");
Console.WriteLine($"C1 --- > {a,-8:C1} -- {b,-8:C1} -- {sum,-8:C1}");
Console.WriteLine($"C2 --- > {a,-8:C2} -- {b,-8:C2} -- {sum,-8:C2}");
Console.WriteLine($"C3 --- > {a,-8:C3} -- {b,-8:C3} -- {sum,-8:C3}");
Outputs the following:
C0 --- > $12 -- $13 -- $26 C1 --- > $12.2 -- $13.3 -- $25.5 C2 --- > $12.20 -- $13.30 -- $25.50 C3 --- > $12.200 -- $13.300 -- $25.500
Upvotes: 1
Reputation: 12815
What you're seeing is correct. The .Sum()
of 12.2 and 13.3 is 25.5, which rounds to 26 when the format is applied.
What you want to do instead is to sum as you iterate through your foreach loop:
@{ var total = 0; }
@foreach (var item in attyData)
{
var cash = Math.Round(item.cashMoney);
total += cash;
<tr>
<td>@String.Format("{0:C0}", cash)</td>
</tr>
}
<tr class="info">
<td>@String.Format("{0:C0}", total)</td>
</tr>
Upvotes: 2