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

10-05 20:46
查看更多