【问题标题】:Convert double to int and keep the decimals c#将double转换为int并保留小数c#
【发布时间】:2016-11-20 20:52:00
【问题描述】:

我有一个任务,我应该创建一个将十进制数 (double) 转换为 int 的方法,但小数也应保留。

例子。 2,33 --放入方法并生成--> 233

这是我到目前为止所做的,它只生成一个四舍五入的数字

    static int MakeDoubleInt(double x)
    {
        int y = (int)x;

        return y;
    }

【问题讨论】:

  • hmmm 可以对2.33 之类的值执行什么操作以使其变为233?要是电脑能成倍增加就好了……
  • hmmm 2.33和233是什么关系?
  • 您要保留多少个十进制数?只有 2 为 (2.33 => 233) ?
  • 当您尝试将2.33 放入double 时,您真正得到的实际上是2.3300000000000000710542735760100185871124267578125(即5246693565886628 / 2**51)。所以你想要什么?如果doubleMath.PI,你会在哪里截断(如果你使用目标类型int 是32 位类型)?

标签: c# int double converter


【解决方案1】:

double 转换为字符串,再次将, TryParse 删除为int

static int MakeDoubleInt(double x)
{
    string str = x.ToString();
    str = str.Replace(",", string.Empty);

    int number;
    int.TryParse(str, out number);

    return number;
}

方法:

int i = MakeDoubleInt(d);

【讨论】:

  • plus1。 [填充文本。请忽略]
【解决方案2】:
static int MakeDoubleInt(double x)
{
    return int.Parse(x.ToString().Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ""));
}

【讨论】:

  • 如果x7E-05 怎么办?如果x56.789012345 怎么办?
猜你喜欢
  • 2011-03-30
  • 2017-02-03
  • 2012-06-01
  • 1970-01-01
  • 2016-07-24
  • 2011-05-10
  • 1970-01-01
  • 2019-02-19
相关资源
最近更新 更多