【问题标题】:Round decimal to nearest 50 and return integer将小数四舍五入到最接近的 50 并返回整数
【发布时间】:2013-12-17 16:32:42
【问题描述】:

这个问题的后续: C# how to always round down to nearest 50

如何将小数四舍五入到最接近的 50 并返回一个 int,我可以执行以下操作但必须有更有效的解决方案?

decimal test = 154.45m;
decimal newValue = Math.Floor(test / 50m) * 50.0m;
int testInt = Convert.ToInt32(newValue);

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以通过转换获得int 部分,而不是转换为int。

    int testInt = (int) Math.Floor(test / 50m) * 50.0m;
    

    我不确定你会从中获得多少性能,但Convert.ToInt32 也会舍入到最接近的 32 位整数,而强制转换只会给你 int 部分

    【讨论】:

    • 应该真的猜到了,显然我的大脑不工作了,谢谢。
    • int testInt = test-(test%50);避免函数调用?
    猜你喜欢
    • 2011-03-21
    • 2022-10-17
    • 1970-01-01
    • 2021-08-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多