我有4个例子。
double a = 1.05;
double b = 0.000056;
double c = 0.7812;
double d = 1.2;
我想做的是首先找出有多少个位置值,在这种情况下...
int inta = 2;
int intb = 6;
int intc = 4;
int intd = 1;
然后我想创建一个用 "0 "代表这些数字的字符串,这是为了ToString()
string stra = ".00";
string strb = ".000000";
string strc = ".0000";
string strd = ".0";
所以我只有一个双数。我需要一个位置值,然后如何创建字符串。
你可以将double转换为字符串,然后得到子串。
double a = 1.05;
// Convert to string
string aString = a.ToString();
// Get substring
string result = aString.Substring(aString.LastIndexOf('.'));
// Get number of decimals
int numDecimals = result.Length - 1;
// Create string based on decimal count
string zeroString = ".";
for (int i = 0; i < numDecimals; i++) {
zeroString += "0";
}
Console.WriteLine(result);
Console.WriteLine(numDecimals);
Console.WriteLine(zeroString);
// .05
// 2
// .00
** 为了确保这对所有的文化都适用,而不仅仅是那些使用'.'作为小数点分隔符的文化,你可以用以下代码来代替:
LastIndexOf('.')
替换为
LastIndexOf(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator)
(感谢@John)
双数并不能准确地表示所有的10进制分数。相反,你应该使用十进制类型。
decimal a = 1.05;
decimal b = 0.000056;
decimal c = 0.7812;
decimal d = 1.2;
decimal e = 1.456000;
a.ToString() == "1.05"
b.ToString() == "0.000056"
c.ToString() == "0.7812"
d.ToString() == "1.2"
e.ToString() == "1.456000"
public static decimal Normalise(this decimal value) => value / 1.000000000000000000000000000000000m;
e.Normalise().ToString() == "1.456"
我认为这个问题摆得不好。具体来说,就是这部分。
首先找出有多少个[小数]位值。
小数点位数是一个表示问题,而不是数字的固有属性。当写 double a = 0.3;
储存在变量中的内容 a
是最接近精确的十进制0.3的双精度值。该值接近于0.3,但并不等同于0.3,因为IEEE-754是基于二进制的,而 0.3
是一个非终止的二进制分数。但是,一旦分配,变量 a
不记得它来自哪里,也不知道源代码中是否有它作为 double a = 0.3;
与。double a = 0.29999999999999999;
.
考虑以下片段。
double a = 0.3;
double b = 0.2999999999999999;
double c = 0.29999999999999999;
Console.WriteLine("a = {0}, b = {1}, c = {2}, a==b = {3}, b==c = {4}, a==c = {5}", a, b, c, a==b, b==c, a==c);
输出是:
a = 0.3, b = 0.3, c = 0.3, a==b = False, b==c = False, a==c = True
这表明变量 a
和 c
即他们持有 确切 同样的值,但其中一个定义为1位小数,而另一个定义为17位小数。重点是,谈论与浮点数相关的小数位数是没有意义的。价值 因为,正如这个例子所显示的,同一个值可以用不同的小数点位数有不同的表示方法......。
作为一个附带的评论,上面也显示了 b
和 c
是不同的值,尽管它们只在小数点后第17位不同。这与 double
型,具有 15至17岁之间 重要的小数点位,这也是为什么一般情况下不能忽略第16、17位的原因。