我有一些集合返回的字段为
2.4200
2.0044
2.0000
Run Code Online (Sandbox Code Playgroud)
我想得到的结果
2.42
2.0044
2
Run Code Online (Sandbox Code Playgroud)
我尝试过String.Format
,但它返回2.0000
并将其设置为N0
舍入其他值.
有没有办法将十进制值四舍五入到.Net中最近的0.05值?
例如:
7.125 - > 7.15
6.66 - > 6.7
如果它现在可用,任何人都可以提供算法吗?
好的,经过一番调查,并且在很大程度上要归功于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
* …
Run Code Online (Sandbox Code Playgroud) 我试图从c#中的十进制数中删除小数点?
例如:我的十进制数是2353.61我想要235361作为结果.我的十进制数是196.06我希望19606是结果.
我怎样才能做到这一点?
我想要带有此签名的 ac# 函数:
int GetSignificantNumberOfDecimalPlaces(decimal d)
Run Code Online (Sandbox Code Playgroud)
调用时它应该表现如下:
GetSignificantNumberOfDecimalPlaces(2.12300m); // returns 3
GetSignificantNumberOfDecimalPlaces(2.123m); // returns 3
GetSignificantNumberOfDecimalPlaces(2.103450m); // returns 5
GetSignificantNumberOfDecimalPlaces(2.0m); // returns 0
GetSignificantNumberOfDecimalPlaces(2.00m); // returns 0
GetSignificantNumberOfDecimalPlaces(2m); // returns 0
Run Code Online (Sandbox Code Playgroud)
即对于给定的小数,我想要小数点右侧的有效小数位数。因此可以忽略尾随零。我的后备方法是将小数点转换为字符串,修剪尾随零,然后以这种方式获取长度。但是有更好的方法吗?
注意:我可能在这里错误地使用了“重要”这个词。示例中所需的返回值应该可以解释我所追求的。
我正在编写计算优惠多席选举的软件.一个常见的要求是固定精度.这意味着必须对具有固定指定精度的值执行所有数学运算,并且结果必须具有相同的精度.固定精度表示小数点后的设定位数.之后的任何数字都将被丢弃.
因此,如果我们假设5位数的精度:
42/139
Run Code Online (Sandbox Code Playgroud)
变为:
42.00000/139.00000 = 0.30215
Run Code Online (Sandbox Code Playgroud)
我在为此编写单元测试时遇到问题.到目前为止,我已经为大小数字写了这两个测试.
public void TestPrecisionBig()
{
PRECISION = 5;
decimal d = Precision(1987.7845263487169386183643876m);
Assert.That(d == 1987.78452m);
}
public void TestPrecisionSmall()
{
PRECISION = 5;
decimal d = Precision(42);
Assert.That(d == 42.00000m);
}
Run Code Online (Sandbox Code Playgroud)
但它评估为42 == 42.00000m不是我想要的.
我该如何测试?我想我可以做一个d.ToString,但这是一个很好的"正确"测试吗?
编辑:我被要求显示我的Precision方法的实现.它不是很优雅,但它有效.
public static decimal Precision(decimal d)
{
if (d == 0) return 0.00000m;
decimal output = Math.Round(d, 6);
string s = output.ToString(CurrentCulture);
char c = char.Parse(CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (s.Contains(c))
{
output = decimal.Parse(s.Substring(0, s.Length - 1));
return output;
} …
Run Code Online (Sandbox Code Playgroud) 我正在寻找String.Format
或ToString()
只decimal
得到小数部分。
'123.56m => "56"