四舍五入为没有浮点的整数

问题描述 投票:0回答:2

我有以下计算:

  1. 0.010140-0.007730
  2. 9564.26-9552.02
  3. 0.00536-0.00024

第一个减法返回0.00241‬。我想将其舍入为241

第二减法返回12.24‬。我想将其舍入为12。 (这个比较容易取整)

第三个是0.00512‬,但我希望它为512

有没有办法做到这一点?请注意,我不需要硬编码的解决方案。我可以轻松地* 100或舍入为硬编码的数字。我不要我想要一个独特的解决方案。

附加信息:

0.00002567将是2567。1.00002567将只是1

c# math rounding
2个回答
1
投票

我的方法

public static int SpecialRounding(decimal input)
{
    if (input >= 1)
    {
        return (int)input;
    }
    else
    {
        while (input % 1 > 0)
        {
            input *= 10;
        }

        return (int)input;
    }
}

https://dotnetfiddle.net/QJcNdj


0
投票

执行类似的操作。

if(your_decimal < 1) 
{ 
  int length=(Convert.tostring(your_decimal)).Length; // 0.00241‬ returns 7 
  string multiplier = "1";

  int(i=1; i< length-1; i++)
  {
    multiplier += "0";
  }

  // at the end of the loop multiplier is = "1000000"

  int result = Convert.ToInt32(multiplier) * your_decimal

}
© www.soinside.com 2019 - 2024. All rights reserved.