[英]C# Rounding a negative exponential double value
我嘗試了所有操作,但無法將非常長的十進制值(指數)的負雙精度值四舍五入為十進制小數。
string str = "-1.7976931348623157E+308";
double d = double.Parse(str);
d = Math.Round(d, 6, MidpointRounding.AwayFromZero);
string str2 = d.ToString();
我想要的結果就是-1.797693,就這么簡單!
需要注意的是,作為LittleBobbyTables建議,也沒有辦法1.xxE+308
是要舍入到1.xx
。 但是假設您不是那個意思,那么您只是在嘗試構建輸出:
string str2 = d.ToString("E6");
E6
中的數字是您要在E表示法前顯示的數字數量。
對於上面的示例, str2
的值為"-1.797693E+308"
。
如果您確實需要對價值進行四舍五入(而且我不太確定為什么會這樣做-為什么要舍棄精度?這不會妨礙您前進),則應保持Round
Call不變。
您根據有效數字的數量寫的此代碼:
/// <summary>
/// Format a number with scientific exponents and specified sigificant digits.
/// </summary>
/// <param name="x">The value to format</param>
/// <param name="significant_digits">The number of siginicant digits to show</param>
/// <returns>The fomratted string</returns>
public static string Sci(this double x, int significant_digits)
{
//Check for special numbers and non-numbers
if (double.IsInfinity(x)||double.IsNaN(x)||x==0)
{
return x.ToString();
}
// extract sign so we deal with positive numbers only
int sign=Math.Sign(x);
x=Math.Abs(x);
// get scientific exponent, 10^3, 10^6, ...
int sci=(int)Math.Floor(Math.Log(x, 10)/3)*3;
// scale number to exponent found
x=x*Math.Pow(10, -sci);
// find number of digits to the left of the decimal
int dg=(int)Math.Floor(Math.Log(x, 10))+1;
// adjust decimals to display
int decimals=Math.Min(significant_digits-dg, 15);
// format for the decimals
string fmt=new string('0', decimals);
if (sci==0)
{
//no exponent
return string.Format("{0}{1:0."+fmt+"}",
sign<0?"-":string.Empty,
Math.Round(x, decimals));
}
int index=sci/3+6;
// with 10^exp format
return string.Format("{0}{1:0."+fmt+"}e{2}",
sign<0?"-":string.Empty,
Math.Round(x, decimals),
sci);
}
這樣Debug.WriteLine((-1.7976931348623157E+308).Sci(7));
產生-179.7693e306
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.