In C# I have the following code and I cant work out why my double values get rendered as a string? When I try to add Tax to Total it reverts to a string?
double Total = 0;
double Tax = 0;
foreach (var Product in ProductList)
{
if (Product.Taxable) Tax = Tax (Product.Price * .1) ;
Total = Total (Product.Price * Product.Qty);
Console.WriteLine("{0} {1} at {2}", Product.Qty, Product.Item, Product.Price.ToString("C"), Product.Taxable, Product.Exempt);
}
Console.WriteLine("Sales Taxes: " Tax.ToString("C"));
Console.WriteLine("Total: " Total.ToString("C"));
Console.WriteLine("Taxes: " Total Tax);
CodePudding user response:
It is because in C# the operator evaluates from left to right:
"Taxes: " Total Tax
first it does "Taxes: " Total
which makes it a string: "Taxes: 1.23"
and then it does: "Taxes: 1.23" Tax
which results in "Taxes: 1.232.34"
for example.
To fix it calculate the sum before or add brackets:
"Taxes: " (Total Tax)
or
var sum = Total Tax
"Taxes: " sum