Dan*_*Tao 17 .net precision decimal significant-digits
好的,经过一番调查,并且在很大程度上要归功于Jon和Hans提供的有用答案,这就是我能够把它放在一起的.到目前为止,我认为它似乎运作良好.当然,我不打赌我的生活完全正确.
public static int GetSignificantDigitCount(this decimal value)
{
/* So, the decimal type is basically represented as a fraction of two
* integers: a numerator that can be anything, and a denominator that is
* some power of 10.
*
* For example, the following numbers are represented by
* the corresponding fractions:
*
* VALUE NUMERATOR DENOMINATOR
* 1 1 1
* 1.0 10 10
* 1.012 1012 1000
* 0.04 4 100
* 12.01 1201 100
*
* So basically, if the magnitude is greater than or equal to one,
* the number of digits is the number of digits in the numerator.
* If it's less than one, the number of digits is the number of digits
* in the denominator.
*/
int[] bits = decimal.GetBits(value);
if (value >= 1M || value <= -1M)
{
int highPart = bits[2];
int middlePart = bits[1];
int lowPart = bits[0];
decimal num = new decimal(lowPart, middlePart, highPart, false, 0);
int exponent = (int)Math.Ceiling(Math.Log10((double)num));
return exponent;
}
else
{
int scalePart = bits[3];
// Accoring to MSDN, the exponent is represented by
// bits 16-23 (the 2nd word):
// http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx
int exponent = (scalePart & 0x00FF0000) >> 16;
return exponent + 1;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有彻底测试过这一切.以下是一些示例输入/输出:
Value Precision 0 1 digit(s). 0.000 4 digit(s). 1.23 3 digit(s). 12.324 5 digit(s). 1.2300 5 digit(s). -5 1 digit(s). -5.01 3 digit(s). -0.012 4 digit(s). -0.100 4 digit(s). 0.0 2 digit(s). 10443.31 7 digit(s). -130.340 6 digit(s). -80.8000 6 digit(s).
使用这段代码,我想我会通过做这样的事情来实现我的目标:
public static decimal DivideUsingLesserPrecision(decimal x, decimal y)
{
int xDigitCount = x.GetSignificantDigitCount();
int yDigitCount = y.GetSignificantDigitCount();
int lesserPrecision = System.Math.Min(xDigitCount, yDigitCount);
return System.Math.Round(x / y, lesserPrecision);
}
Run Code Online (Sandbox Code Playgroud)
不过,我还没有真正完成这项工作.任何想分享想法的人:非常感谢!
假设我已经写了这段代码:
decimal a = 1.23M;
decimal b = 1.23000M;
Console.WriteLine(a);
Console.WriteLine(b);
Run Code Online (Sandbox Code Playgroud)
以上将输出:
1.23 1.23000
我发现如果我使用decimal.Parse("1.23")for a和decimal.Parse("1.23000")for 这也有效b(这意味着这个问题适用于程序接收用户输入的情况).
很明显,一个decimal值在某种程度上"意识到"我称之为精确度的东西.但是,decimal除了ToString自身之外,我看不到提供任何访问方式的类型的成员.
假设我想将两个decimal值相乘并将结果修剪为不太精确的参数的精度.换一种说法:
decimal a = 123.4M;
decimal b = 5.6789M;
decimal x = a / b;
Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)
以上输出:
21.729560302171195125816619416
我要问的是:我怎么能写一个会返回的方法21.73(因为123.4M有四个有效数字)?
要清楚:我意识到我可以调用ToString两个参数,计算每个字符串中的有效数字,并使用此数字来计算计算结果.如果可能的话,我正在寻找一种不同的方式.
(我也认识到,在你处理显著数字大多数情况下,你可能并不需要使用的decimal类型.但是,我这么问是因为,正如我在开头提到的,该decimal类型的出现,包括有关信息精确,double但不是,据我所知.)
您可以用来Decimal.GetBits获取原始数据,并从中计算出来。
不幸的是,我现在没有时间编写示例代码 -BigInteger如果您使用 .NET 4,您可能需要使用一些操作 - 但希望这能让您继续前进。只需计算出精度,然后调用Math.Round原始结果很可能是一个好的开始。
| 归档时间: |
|
| 查看次数: |
3867 次 |
| 最近记录: |