string input = Console.ReadLine();
decimal sum = Convert.ToDecimal(input);
if (sum >= (decimal)500.01)
{
//40% and 8 dollars off shipping costs are taken off total amount
decimal totalprice;
totalprice = (sum - 8) * .60m;
Math.Truncate(totalprice);
Console.WriteLine("Your final cost is:${0:0.00}", totalprice);
Console.Read();
问题是,当我在我的程序中输入价格 598.88 美元时,我应该得到 354.52。
数学:
598.88 - 8 = 590.88. 590.88 * 60% = 354.528
我实际上得到了 354.53,因为 C# 向上取整而不是向下取整。 例如,
如果我得到像 519.998 这样的答案,我希望它保持在 519.99。 另一个例子,如果我得到像 930.755 这样的答案,我希望它保持在 930.75。
我查看了一些答案,但 Math.Truncate 显然对我不起作用,使用 *100/100 技巧也不起作用。请记住,我是一名新学生,所以,如果答案是菜鸟安全的,那就太好了。谢谢。
请您参考如下方法:
* 100/100 可以正常使用,您可能使用错了。试试下面这个:
decimal totalprice = TruncateToTwoDigits((sum - 8) * .60m);
Console.WriteLine("Your final cost is:${0:0.00}", totalprice);
...
private static decimal TruncateToTwoDigits(decimal Value)
{
int adjusted = (int)Math.Truncate(Value * 100m);
return adjusted / 100m;
}
作为旁注,Math.Truncate 返回截断值,它不会像您的代码所暗示的那样更改输入参数。
