c# - 如何在 C# 中将 System.Decimal 位转换为字符串?

标签 c# .net decimal

我希望能够从 System.Decimal 值中获取位,然后将其转换为该值的字符串表示形式,很像 Decimal.ToString() 可以,但我很难想出算法。

所以我有这样的东西:

decimal d = 1403.45433M;
int[] nDecimalBits = decimal.GetBits(d);

// How to convert the 4 integers in nDecimalBits to a string
// that contains "1403.45433"?

我知道十进制的二进制布局 - 前 3 个整数包含值位,最后一个整数包含符号位和比例因子。

我尝试使用各种搜索词搜索该算法,但小数主要用作“ float ”的同义词,因此我的搜索找到了不相关问题的答案。

如有任何帮助,我们将不胜感激。

编辑:为了响应一些答案,我需要将位发送到需要重建值的不同平台。 System.Decimal 及其任何成员函数在那里不可用,因此我需要获取这些位并将它们转换为字符串。

如果我有选择,我显然会使用 ToString() 但这样我就不需要问了。

最佳答案

您可以使用 Decimal 构造函数 Decimal(Int32[])将您的值(value)转换回来:

Decimal Constructor (Int32[])

Initializes a new instance of Decimal to a decimal value represented in binary and contained in a specified array.

之后,您可以根据需要使用 ToString。 示例:

decimal d = 1403.45433M;
int[] nDecimalBits = decimal.GetBits(d);

decimal d2 = new decimal(nDecimalBits);
string s = d2.ToString();

关于c# - 如何在 C# 中将 System.Decimal 位转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5469505/

相关文章:

c# - 创建未知类型的实例

c# - 从点云到实体网格

c# - 是否可以创建一个引用不等于任何其他字符串的字符串?

c# - 并行启动多个异步任务的最佳方式?

ios - 如何避免在 NSNumberFormatter 中四舍五入

c# - 从 C# 配置 *.scr 文件

c# - 使用枚举值表示两个枚举值

c# - 字符串转十进制之谜

javascript - Highcharts - 散点图 : set decimals of x-axis and y-axis

c# - 如何将 "AutoSize"设置为 Excel 工作表列? (非营利组织)