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
返回截断的值,它不会像您的代码所暗示的那样更改输入参数。