如何在 .net 中将整数转换为十进制数

5

如何将 int 转换为 decimal 示例:将 12 转换为 12.0

我尝试了下面的方法,但没有成功

int i = 10;
Decimal newValue = Decimal.parse(i)

并且

Decimal newValue  = Convert.ToDecimal(i)

3
你知道在同一作用域内,两个不同的变量不能拥有相同的名称吗? - Iłya Bursov
1
在一个崇高的黑暗领主的话中,你需要一位老师。 - Anthony Pegram
2
有一个显式的类型转换操作符 - 只需执行 decimal d = (decimal)i; - D Stanley
你为什么认为所有的答案(基本上都是说你尝试过的)都不起作用?你是否像将值写入字符串一样进行操作?如果是这样,可能会忽略 .0。 - Pheonyx
我在十进制newValue中看到了值10,而不是10.0。 - user166013
int x = 100; decimal y = x * 0.01m; //1.00 https://dotnetfiddle.net/t3j82Z - Vinicius.Beloni
3个回答

14
您无法更改局部变量的类型:
  // i is integer
  int i = 10;
  // and now i become decimal 
  decimal i = decimal.parse(i); // <- doesn't compile

但是您可以创建另一个本地变量:

  int i = 10;
  decimal d = i; // d == 10M

而 .Net 可以为您将 i 转换为 decimal(所以您有整数 i == 10 和十进制数 d == 10m)。使用动态类型存在一种 奇特的 可能性。

  dynamic i = 15;           // i is int
  i = Convert.ToDecimal(i); // now i is decimal; "(decimal) i;" will do as well

但我怀疑你是否需要它。如果您坚持使用Parse(),则应该放置一个丑陋的

  decimal d = decimal.Parse(i.ToString());

我们仅从String表示中解析。

编辑:

但是十进制值仍然只包含整数,即10而不是10.0

数学上说

  10 == 10.0 == 10.00 == 10.000 == ...

因此,如果您想更改表示,应使用格式化:
  Console.Write(d.ToString("F1")); // F1 - 1 digit after the decimal point

如果是 decimal 类型(而不是 double),你可以使用一个(不太光彩?)的技巧

  decimal d = i + 0.0m;

  Console.Write(d); // 10.0

尝试了以上所有方法,但是十进制值仍然只包含整数,即10而不是10.0。 - user166013

1

decimal(或Decimal)定义了一个隐式转换操作符,使您可以简单地编写如下内容:

int i = 10;
decimal d = i;

0

尝试一下

int i = 10;
decimal d = new decimal(i);

请注意,您无法在运行时将i的类型从int更改为decimal;您需要有两个变量--一个inti)和一个decimald)。

抱歉打错字了,我已经更新了。但是隐式转换没有起作用。 - user166013

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接