【问题标题】:In C#, how do I get required number of decimal point values without rounding? [duplicate]在 C# 中,如何在不四舍五入的情况下获得所需的小数点值? [复制]
【发布时间】:2011-08-08 14:00:00
【问题描述】:

可能重复:
C# Double - ToString() formatting with two decimal places but no rounding

我正在使用浮点数,我想在不进行任何四舍五入的情况下获得小数位数。

例如。浮动 x = 12.6789 如果我想要最多 2 个小数点,那么我应该得到 (x = 12.67) 而不是 (x = 12.68),这会在进行舍入时发生。

请建议最好的方法。

【问题讨论】:

  • 你试过什么?什么没用?请发布您的代码并说明您遇到问题的地方。

标签: c# floating-point rounding


【解决方案1】:

您应该可以为此使用Math.Truncate()

decimal x = 12.6789m;
x = Math.Truncate(x * 100) / 100; //This will output 12.67

【讨论】:

    【解决方案2】:

    您可以通过强制转换来实现:

    float x = 12.6789;
    float result = ((int)(x * 100.0)) / 100.0;
    

    【讨论】:

      【解决方案3】:

      这可能有一个框架调用,但你总是可以这样写:

      //Scale up, floor, then round down.
      //ie: 1.557 
      //    scaled up: 155.7
      //    floord:  155
      //    scaled down: 1.55
      public float MyTruncate(float f, int precision){
         float scale = precision * 10;
         return (Math.Floor(f * scale)) / scale;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多